package com.realnet.DynamicDashbard.services;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.realnet.DynamicDashbard.entities.ChartType;
import com.realnet.DynamicDashbard.entities.DynamicField;
import com.realnet.DynamicDashbard.repositories.ChartTypeRepository;
import com.realnet.DynamicDashbard.repositories.DynamicFieldRepository;

@Service
public class DynamicFieldService {

	@Autowired
	private DynamicFieldRepository dynamicFieldRepository;

	@Autowired
	private ChartTypeRepository chartTypeRepository;

	public List<DynamicField> getAllDynamicFields() {
		return dynamicFieldRepository.findAll();
	}

	public List<DynamicField> getDynamicFieldsByChartType(Long chartTypeId) {
		ChartType chartType = chartTypeRepository.findById(chartTypeId)
				.orElseThrow(() -> new RuntimeException("ChartType not found with id: " + chartTypeId));
		return dynamicFieldRepository.findByChartType(chartType);
	}

	public Optional<DynamicField> getDynamicFieldById(Long id) {
		return dynamicFieldRepository.findById(id);
	}

	public DynamicField saveDynamicField(DynamicField dynamicField) {
		return dynamicFieldRepository.save(dynamicField);
	}

	public DynamicField updateDynamicField(Long id, DynamicField dynamicFieldDetails) {
		DynamicField dynamicField = dynamicFieldRepository.findById(id)
				.orElseThrow(() -> new RuntimeException("DynamicField not found with id: " + id));

		dynamicField.setFieldName(dynamicFieldDetails.getFieldName());
		dynamicField.setFieldLabel(dynamicFieldDetails.getFieldLabel());
		dynamicField.setFieldType(dynamicFieldDetails.getFieldType());
		dynamicField.setFieldOptions(dynamicFieldDetails.getFieldOptions());
		dynamicField.setIsRequired(dynamicFieldDetails.getIsRequired());
		dynamicField.setShowInUi(dynamicFieldDetails.getShowInUi());
		dynamicField.setSortOrder(dynamicFieldDetails.getSortOrder());

		return dynamicFieldRepository.save(dynamicField);
	}

	public void deleteDynamicField(Long id) {
		DynamicField dynamicField = dynamicFieldRepository.findById(id)
				.orElseThrow(() -> new RuntimeException("DynamicField not found with id: " + id));
		dynamicFieldRepository.delete(dynamicField);
	}
}