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

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.springframework.context.ApplicationContext;

import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.util.ItsmSmsSender;
import com.eactive.eai.rms.onl.manage.rule.aurora.IocmRstService;

@SuppressWarnings("rawtypes")
public class ItsmIocmCheckListJob implements Job {
	private static final Logger logger = Logger.getLogger(ItsmIocmCheckListJob.class);
	private static final String DATE_FORMAT = "yyyyMMdd";
	private transient MonitoringContext monitoringContext;
	
	IocmRstService iocmRstService;
	
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		ApplicationContext appContext = null;
		try {
			appContext = (ApplicationContext)context.getScheduler().getContext().get("applicationContext");
		} catch (SchedulerException e) {
			logger.error("applicationContext get module error",e);
			return ;
		}
		monitoringContext    = (MonitoringContext)appContext.getBean("monitoringContext");
		this.iocmRstService = (IocmRstService) appContext.getBean("iocmRstService");
		run();
	}
	
	private void run() {
		StringBuffer sbuffer = new StringBuffer();
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
		String rstVal = "1";	// 정상 : 1, 비정상 : 0
		try {
			String today = sdf.format(new Date());
			String yesterday = getBeforeDateString(sdf);
			yesterday = yesterday + "180000";
			today = today + "060000";
			
			//테이블 변경 TSEAIRM29 (MONITORING)
			DataSourceType dataType = DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.MONITORING);
	  		DataSourceContextHolder.setDataSourceType(dataType);
	  		 
			/*
			 * 전일 18:00 ~ 당일 06:00 사이 적용 패키지 중에 아래 경우의 패키지명 추출
			 * 1. 적용이 되지 않은 경우	"EAIAplyYn" = 'N'	OR 
			 * 2. 오류가 발생한 경우	"ChmnErrcd" != 000
			 */
			List<Map> faultList = iocmRstService.selectIocmFaultList(yesterday, today);
			if(faultList != null && faultList.size() > 0 ){
				rstVal = "0";
				for (Map map : faultList) {
					String packNo = (String) map.get("MODFIMGTPCKAGNO");
					sbuffer.append(packNo.trim()).append("/");
				}
				boolean status = sendCheckList(rstVal);
				logger.info("status ["+ status +"] - "+ rstVal + " :"+ sbuffer.toString());
			}else{
				logger.info("ItsmLocmCheckList] faultList > Empty ! ");
				rstVal = "1";  //정상
				sendCheckList(rstVal);
			}
		} catch (Exception e) {
			logger.error(e.toString());
		}
	}
	
	private String getBeforeDateString(SimpleDateFormat sdf) {
		Calendar calendar = Calendar.getInstance();
		if (calendar.get(Calendar.DAY_OF_WEEK) == 2) {
			// 월요일이면 금요일을 전일로 설정
			calendar.add(Calendar.DATE, -3);
		} else {
			calendar.add(Calendar.DATE, -1);
		}
		return sdf.format(calendar.getTime());
	}
	
	public boolean sendCheckList(String rstVal) {
		String[] info = null;
		String chk_ip = monitoringContext.getStringProperty(MonitoringContext.ITSMCHECKLIST_IP,"");
		String chk_port = monitoringContext.getStringProperty(MonitoringContext.ITSMCHECKLIST_PORT,"");
		
		String[] resultValue = {chk_ip, chk_port};
		info = resultValue;
		if(logger.isInfoEnabled()) logger.info("chk ip:"+info[0] + "  port:"+info[1]);
		if(logger.isInfoEnabled()) logger.info("ip:"+info[0] + "  port:"+info[1]);
		
		System.setProperty("ItsmCheckListIP", 	info[0]); 
		System.setProperty("ItsmCheckListPORT", info[1]);
		
		boolean isSuccess = true;
		
		try{
			isSuccess = ItsmSmsSender.sendCheckList("004", rstVal, "", "packageName");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("sendCheckList error : ",e);
			isSuccess = false;
		}
		return isSuccess;
		
	}
}
