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.ChartTemplate;
import com.realnet.DynamicDashbard.entities.ChartType;
import com.realnet.DynamicDashbard.repositories.ChartTemplateRepository;
import com.realnet.DynamicDashbard.repositories.ChartTypeRepository;

@Service
public class ChartTemplateService {

	@Autowired
	private ChartTemplateRepository chartTemplateRepository;

	@Autowired
	private ChartTypeRepository chartTypeRepository;

	public List<ChartTemplate> getAllChartTemplates() {
		return chartTemplateRepository.findAll();
	}

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

	public Optional<ChartTemplate> getChartTemplateById(Long id) {
		return chartTemplateRepository.findById(id);
	}

	public ChartTemplate saveChartTemplate(ChartTemplate chartTemplate) {
		return chartTemplateRepository.save(chartTemplate);
	}

	public ChartTemplate updateChartTemplate(Long id, ChartTemplate chartTemplateDetails) {
		ChartTemplate chartTemplate = chartTemplateRepository.findById(id)
				.orElseThrow(() -> new RuntimeException("ChartTemplate not found with id: " + id));

		chartTemplate.setTemplateName(chartTemplateDetails.getTemplateName());
		chartTemplate.setTemplateHtml(chartTemplateDetails.getTemplateHtml());
		chartTemplate.setTemplateCss(chartTemplateDetails.getTemplateCss());
		chartTemplate.setIsDefault(chartTemplateDetails.getIsDefault());

		return chartTemplateRepository.save(chartTemplate);
	}

	public void deleteChartTemplate(Long id) {
		ChartTemplate chartTemplate = chartTemplateRepository.findById(id)
				.orElseThrow(() -> new RuntimeException("ChartTemplate not found with id: " + id));
		chartTemplateRepository.delete(chartTemplate);
	}
}