package com.eactive.eai.rms.data.entity.man.scheduler;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.common.util.UUIDGenerator;
import com.eactive.eai.rms.data.jpa.AbstractEMSDataSerivce;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.jpa.impl.JPAQuery;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@Transactional(transactionManager = "transactionManagerForEMS")
public class JobHistoryService extends AbstractEMSDataSerivce<JobHistory, String, JobHistoryRepository> {

	private JobInfoService jobInfoService;

	@Autowired
	public JobHistoryService(JobInfoService jobInfoService) {
		this.jobInfoService = jobInfoService;
	}

	public String findRecentStatus(String jobName, String instanceName) {
		QJobHistory qJobHistory = QJobHistory.jobHistory;

		JPAQuery<String> maxEndDateQuery = getJPAQueryFactory()
				.select(qJobHistory.endDate.max())
				.from(qJobHistory)
				.where(qJobHistory.jobName.eq(jobName).and(qJobHistory.instanceName.eq(instanceName)));

		return getJPAQueryFactory()
				.select(qJobHistory.status)
				.from(qJobHistory)
				.where(qJobHistory.endDate.eq(maxEndDateQuery))
				.fetchFirst(); // unique 에러 발생 대응
				//.fetchOne(); 
	}

	public void updateStatus(String jobName, String startDate, String endDate, String status) throws Exception {
		String instanceName = System.getProperty("inst.Name");
		String uuid = UUIDGenerator.getUUID();

		JobInfo jobInfo = jobInfoService.getById(jobName);

		if (StringUtils.equalsAnyIgnoreCase(jobInfo.getChkStatus(), "Y", "E")) {

			String rctStatus = findRecentStatus(jobName, instanceName); // 최근 Data 조회

			// log.info("[DHJEONG]1_rctStatus-->{}, jobName-->{}, instanceName-->{}", rctStatus, jobName, instanceName);

			if (!status.equals(rctStatus) || !"E".equals(jobInfo.getChkStatus())) {
				// 'Y' 이면 무조건 등록, 'E' 이면 ==> Status 바뀌면 등록
				JobHistory jobHistory = new JobHistory();
				jobHistory.setUuid(uuid);
				jobHistory.setJobName(jobName);
				jobHistory.setStartDate(startDate);
				jobHistory.setEndDate(endDate);
				jobHistory.setStatus(status);
				jobHistory.setInstanceName(instanceName);

				save(jobHistory);
			}
		}
	}

	public Page<JobHistory> findAll(Pageable pageable, String searchStartTime, String searchEndTime,
			String searchJobName, String searchInstanceName) {

		QJobHistory qJobHistory = QJobHistory.jobHistory;
		BooleanExpression predicate = qJobHistory.startDate
				.between(searchStartTime, searchEndTime)
				.or(qJobHistory.endDate.between(searchStartTime, searchEndTime));

		if (StringUtils.isNotBlank(searchJobName)) {
			predicate = predicate.and(qJobHistory.jobName.containsIgnoreCase(searchJobName));
		}

		if (StringUtils.isNotBlank(searchInstanceName)) {
			predicate = predicate.and(qJobHistory.instanceName.containsIgnoreCase(searchInstanceName));
		}

		return repository.findAll(predicate, pageable);
	}

}
