package com.eactive.eai.rms.onl.manage.adapter.spcftmadapter;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.Date;

import org.apache.log4j.Logger;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class AdapterSchedulerUtil {
	@Autowired
	@Qualifier("scheduler")
	private static Scheduler scheduler;

	public void setScheduler(Scheduler scheduler) {
		AdapterSchedulerUtil.scheduler = scheduler;
		logger.debug("scheduler : " + this.scheduler);
	}

	private static final Logger logger = Logger.getLogger(AdapterSchedulerUtil.class);

	static String adapterGroup = "ADAPTER_SCHEDULE";

	private static String getTriggerName(String jobName) {
		return jobName + "-trigger";
	}

	public static void deleteJob(Scheduler scheduler, String jobNm) throws Exception {
		JobKey key = new JobKey(jobNm, adapterGroup);
		scheduler.deleteJob(key);
		if (logger.isInfoEnabled())
			logger.info(jobNm + " has been scheduled to deleted");
	}

	public static void addJob(Scheduler scheduler, AdapterJobInfo info) throws Exception {
		if (!"0".equals(info.getAdptrMngDstCd())) {

			// if("ALL".equals(info.getInstanceName()) ||
			// ContainerUtil.getInstanceName().equals(info.getInstanceName()) ){
			@SuppressWarnings("rawtypes")
			// Class jobClass = Class.forName(info.getJobClassName());
			Class jobClass = Class.forName("com.eactive.eai.rms.onl.manage.adapter.spcftmadapter.AdapterSchedulerJob");

			@SuppressWarnings("unchecked")
			JobBuilder jobBuilder = newJob(jobClass);

			jobBuilder = jobBuilder.withIdentity(info.getJobName(), adapterGroup);
			// for(String key : info.getKeySet()){
			jobBuilder.usingJobData("adptrBzwkGroupName", info.getAdptrBzwkGroupName());
			jobBuilder.usingJobData("startStop", info.getStartStop());
			jobBuilder.usingJobData("serverName", info.getServerName());
			jobBuilder.usingJobData("adptrMngDstCd", info.getAdptrMngDstCd());
			jobBuilder.usingJobData("adtrSvrInstNm", info.getAdtrSvrInstNm());

			// }
			JobDetail job = jobBuilder.build();

			CronTrigger trigger = newTrigger()
					.withIdentity(getTriggerName(info.getJobName()), adapterGroup)
					.withSchedule(cronSchedule(info.getCronExp()))
					.build();

			Date ft = scheduler.scheduleJob(job, trigger);
			if (logger.isInfoEnabled())
				logger
						.info(job.getKey() + " has been scheduled to run at: " + ft
								+ " and repeat based on expression: " + trigger.getCronExpression());
			// }

		}
	}

}
