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

@Service
public class ComponentPropertyService {

	@Autowired
	private ComponentPropertyRepository componentPropertyRepository;

	@Autowired
	private UiComponentRepository uiComponentRepository;

	public List<ComponentProperty> getAllComponentProperties() {
		return componentPropertyRepository.findAll();
	}

	public List<ComponentProperty> getComponentPropertiesByComponent(Long componentId) {
		UiComponent component = uiComponentRepository.findById(componentId)
				.orElseThrow(() -> new RuntimeException("UiComponent not found with id: " + componentId));
		return componentPropertyRepository.findByComponent(component);
	}

	public Optional<ComponentProperty> getComponentPropertyById(Long id) {
		return componentPropertyRepository.findById(id);
	}

	public ComponentProperty saveComponentProperty(ComponentProperty componentProperty) {
		return componentPropertyRepository.save(componentProperty);
	}

	public ComponentProperty updateComponentProperty(Long id, ComponentProperty componentPropertyDetails) {
		ComponentProperty componentProperty = componentPropertyRepository.findById(id)
				.orElseThrow(() -> new RuntimeException("ComponentProperty not found with id: " + id));

		componentProperty.setPropertyName(componentPropertyDetails.getPropertyName());
		componentProperty.setPropertyValue(componentPropertyDetails.getPropertyValue());
		componentProperty.setPropertyType(componentPropertyDetails.getPropertyType());

		return componentPropertyRepository.save(componentProperty);
	}

	public void deleteComponentProperty(Long id) {
		ComponentProperty componentProperty = componentPropertyRepository.findById(id)
				.orElseThrow(() -> new RuntimeException("ComponentProperty not found with id: " + id));
		componentPropertyRepository.delete(componentProperty);
	}
}