package com.eactive.eai.rms.common.scheduler;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.springframework.context.ApplicationContext;

import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.data.entity.man.scheduler.JobHistoryService;

public class JobLoggingListener implements JobListener {

	@Override
	public String getName() {
		return "JobLoggingListener";
	}

	@Override
	public void jobExecutionVetoed(JobExecutionContext arg0) {
		//
	}

	@Override
	public void jobToBeExecuted(JobExecutionContext arg0) {
		//
	}

	@Override
	public void jobWasExecuted(JobExecutionContext context, JobExecutionException exception) {

		ApplicationContext appContext = null;
		String jobName = context.getJobDetail().getKey().getName();
		String status = "success";
		// 스케줄러 그룹
		String adpaterGrpJob = context.getJobDetail().getKey().getGroup();

		Logger logger = Logger.getLogger(context.getJobDetail().getKey().getName());

		if (exception != null && !StringUtils.isEmpty(exception.getMessage())) {
			logger.error(jobName + " Scheduler Job has been Failed");
			status = "failed";

			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			exception.printStackTrace(pw);
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String startDate = (dateFormat).format(context.getFireTime());
		String endDate = DatetimeUtil.getCurrentTimeMillis();

		try {
			if (!context.getScheduler().getContext().isEmpty()) {
				appContext = (ApplicationContext) context.getScheduler().getContext().get("applicationContext");
				if (!context.getScheduler().isShutdown()) {
					logger.debug("★★★★★ JobAspect Scheduler GroupName: " + adpaterGrpJob);

					// 모니터링 스케줄러
					DataSourceContextHolder
							.setDataSourceType(
									DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.MONITORING));
					JobHistoryService jobHistoryService = appContext.getBean(JobHistoryService.class);
					jobHistoryService.updateStatus(jobName, startDate, endDate, status);
				} else {
					logger.error("The Context Information is not Valid : " + context);
				}
			}
		} catch (Exception e) {
			logger.error("Updating Scheduler Status has been Failed", e);
		}

	}

}
