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

import java.util.List;

import javax.persistence.EntityNotFoundException;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.apim.portal.monitoringcode.entity.MonitoringCode;
import com.eactive.apim.portal.monitoringcode.entity.MonitoringCodeId;
import com.eactive.apim.portal.monitoringcode.entity.QMonitoringCode;
import com.eactive.eai.data.jpa.AbstractDataService;
import com.eactive.eai.rms.data.entity.man.monitoringCode.repository.MonitoringCodeRepository;
import com.querydsl.core.types.dsl.BooleanExpression;

@Service
@Transactional(transactionManager = "transactionManagerForEMS")
public class MonitoringCodeService extends AbstractDataService<MonitoringCode, MonitoringCodeId, MonitoringCodeRepository> {

	public List<MonitoringCode> findByIdCodegroup(String codeGroup, String sortColumn) {
		QMonitoringCode qMonitoringCode = QMonitoringCode.monitoringCode;
		BooleanExpression predicate = qMonitoringCode.id.codeGroup.eq(codeGroup);
		Sort sort = Sort.by(Sort.Direction.ASC, sortColumn);
		return (List<MonitoringCode>) repository.findAll(predicate, sort);
	}

	public Iterable<MonitoringCode> findByIdCodegroup(String codeGroup) {
		QMonitoringCode qMonitoringCode = QMonitoringCode.monitoringCode;
		BooleanExpression predicate = qMonitoringCode.id.codeGroup.eq(codeGroup);
		return repository.findAll(predicate);
	}
	public Iterable<MonitoringCode> findByIdCodegroupAndUseYn(String codeGroup) {
		QMonitoringCode qMonitoringCode = QMonitoringCode.monitoringCode;
		BooleanExpression predicate = qMonitoringCode.id.codeGroup.eq(codeGroup)
								 .and(qMonitoringCode.useYn.eq("Y"));
		return repository.findAll(predicate, Sort.by("id.code"));
	}

	public String findCodenameById(MonitoringCodeId monitoringCodeId) {
		return repository.findById(monitoringCodeId).orElseThrow(() -> new EntityNotFoundException(
						"MonitoringCode not found for codeGroup: " + monitoringCodeId.getCodeGroup() + " and code: " + monitoringCodeId.getCode()))
				.getCodeName();
	}

	public Page<MonitoringCode> findAll(Pageable pageable, String codeGroup, String searchCodeName) {
		QMonitoringCode qMonitoringCode = QMonitoringCode.monitoringCode;
		BooleanExpression predicate = qMonitoringCode.id.codeGroup.eq(codeGroup)
				.and(qMonitoringCode.codeName.containsIgnoreCase(searchCodeName));
		return repository.findAll(predicate, pageable);
	}

}
