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.UiComponent;
import com.realnet.DynamicDashbard.repositories.ChartTypeRepository;
import com.realnet.DynamicDashbard.repositories.UiComponentRepository;

@Service
public class UiComponentService {

	@Autowired
	private UiComponentRepository uiComponentRepository;

	@Autowired
	private ChartTypeRepository chartTypeRepository;

	public List<UiComponent> getAllUiComponents() {
		return uiComponentRepository.findAll();
	}

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

	public Optional<UiComponent> getUiComponentById(Long id) {
		return uiComponentRepository.findById(id);
	}

	public UiComponent saveUiComponent(UiComponent uiComponent) {
		return uiComponentRepository.save(uiComponent);
	}

	public UiComponent updateUiComponent(Long id, UiComponent uiComponentDetails) {
		UiComponent uiComponent = uiComponentRepository.findById(id)
				.orElseThrow(() -> new RuntimeException("UiComponent not found with id: " + id));

		uiComponent.setComponentName(uiComponentDetails.getComponentName());
		uiComponent.setComponentType(uiComponentDetails.getComponentType());
		uiComponent.setDisplayLabel(uiComponentDetails.getDisplayLabel());
		uiComponent.setPlaceholder(uiComponentDetails.getPlaceholder());
		uiComponent.setIsRequired(uiComponentDetails.getIsRequired());
		uiComponent.setSortOrder(uiComponentDetails.getSortOrder());

		return uiComponentRepository.save(uiComponent);
	}

	public void deleteUiComponent(Long id) {
		UiComponent uiComponent = uiComponentRepository.findById(id)
				.orElseThrow(() -> new RuntimeException("UiComponent not found with id: " + id));
		uiComponentRepository.delete(uiComponent);
	}
}