package com.eactive.eai.rms.onl.common.service;

import com.eactive.eai.rms.onl.common.service.ums.UmsDispatchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Admin Job Configuration
 * ----------------------
 * Job ID: UMSDISPATCHJOB
 * Description: UMS 메시지 발송
 * Class: com.eactive.eai.rms.onl.common.service.UmsDispatchJob
 */
// Cron Expression: */5 * * * * ?
@Slf4j
public class UmsDispatchJob implements Job {

	 private final UmsDispatchService umsDispatchService;

    @Autowired
    public UmsDispatchJob(UmsDispatchService umsDispatchService) {
    	this.umsDispatchService = umsDispatchService;
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        log.info("Starting Message Dispatch Job...");

        // inst.Name 이 지정된 경우 해당 인스턴스에서만 동작
        String jobInstName = context.getJobDetail().getJobDataMap().getString("execute.instances");
        if (StringUtils.isNotEmpty(jobInstName)) {
            log.debug("Job 실행 인스턴스 명이 지정되어 있음 - {}", jobInstName);
            jobInstName = jobInstName.toLowerCase();
            Set<String> propInstances = Arrays.stream(jobInstName.split(",")).map(String::trim).collect(Collectors.toSet());

            String instanceName = System.getProperty("inst.Name");
            if (StringUtils.isNotEmpty(instanceName)) {
                log.debug("현재 인스턴스 명 : {}", instanceName);
                instanceName = instanceName.trim().toLowerCase();

                if (!propInstances.contains(instanceName)) {
                    log.debug("Job 인스턴스명과 현재 인스턴스명이 다름. 종료 처리");
                    return;
                }
            }
        }

        try {
            umsDispatchService.processMessages();
        } catch (Exception e) {
            log.error("Failed to process messages", e);            
            throw new JobExecutionException(e);
        }
    }
}
