package com.eactive.eai.rms.data.entity.man.monitoringProperty.service;

import java.util.Optional;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.data.jpa.AbstractDataService;
import com.eactive.eai.rms.data.entity.man.monitoringProperty.MonitoringProperty;
import com.eactive.eai.rms.data.entity.man.monitoringProperty.MonitoringPropertyId;
import com.eactive.eai.rms.data.entity.man.monitoringProperty.QMonitoringProperty;
import com.eactive.eai.rms.data.entity.man.monitoringProperty.repository.MonitoringPropertyRepository;
import com.querydsl.core.types.dsl.BooleanExpression;

@Service
@Transactional
@Slf4j
public class MonitoringPropertyService
		extends AbstractDataService<MonitoringProperty, MonitoringPropertyId, MonitoringPropertyRepository> {

	public String findPrpty2ValById(String prptyGroupName, String key) {
		MonitoringPropertyId id = new MonitoringPropertyId();
		id.setPrptyGroupName(prptyGroupName);
		id.setPrptyName(key);

		Optional<MonitoringProperty> property = repository.findById(id);
		return property.map(MonitoringProperty::getPrpty2Val).orElse(null);
	}
	
	public String getPrpty2ValById(String prptyGroupName, String prptyName) {
		MonitoringPropertyId id = new MonitoringPropertyId();
		id.setPrptyGroupName(prptyGroupName);
		id.setPrptyName(prptyName);
		
		Optional<MonitoringProperty> property = repository.findById(id);
		return property.map(MonitoringProperty::getPrpty2Val).orElse(null);
	}

	public String getPropertyValue(String prptyGroupName, String prptyName, String defaultValue) {
		MonitoringPropertyId id = new MonitoringPropertyId();
		id.setPrptyGroupName(prptyGroupName);
		id.setPrptyName(prptyName);

		Optional<MonitoringProperty> property = repository.findById(id);
		if (property.isPresent()) {
			String value = property.get().getPrpty2Val();
			if (value != null && !value.isEmpty()) {
				log.debug("getPropertyValue - {} : {}", prptyName, value);
				return value;
			}
		}

		log.debug("getPropertyValue - {} : {} (defaultValue)", prptyName, defaultValue);
		return defaultValue;
	}

	public Iterable<MonitoringProperty> findAllByIdPrptyName(String prptyName) {
		BooleanExpression predicate = QMonitoringProperty.monitoringProperty.id.prptyName.eq(prptyName);
		return repository.findAll(predicate);
	}

	public void refresh(MonitoringProperty p) {
		repository.refresh(p);
	}

}
