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

import java.util.HashMap;

import org.apache.log4j.Logger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;


public class AdapterScheduleInit implements ApplicationListener  {


	@Autowired
	@Qualifier("scheduler")
	private Scheduler scheduler;
	
	@Autowired
	@Qualifier("spcfTmAdapterDao")
	private SpcfTmAdapterDao spcfTmAdapterDao;

	public void setScheduler(Scheduler scheduler) {
		this.scheduler = scheduler;
	}
	
	private static final Logger logger = Logger.getLogger(AdapterScheduleInit.class);

	@Override
	public void onApplicationEvent(ApplicationEvent arg0) {
		if (arg0 instanceof org.springframework.context.event.ContextRefreshedEvent){
			//org.springframework.context.event.ContextRefreshedEvent a = (org.springframework.context.event.ContextRefreshedEvent)arg0;
			HashMap<String, AdapterJobInfo> map =null;
			HashMap<String, Object> paramMap = new HashMap<String, Object>();
			try {
			  	map = spcfTmAdapterDao.getAdapterSchedule(paramMap);
			} catch (Exception e2) {
				//e2.printStackTrace();
				map = new HashMap<String, AdapterJobInfo>();
			}
			
			AdapterJobInfo info = null;		
			for(String key : map.keySet()) {
				info = map.get(key);
				try {
					AdapterSchedulerUtil.deleteJob(this.scheduler, info.getJobName());
					AdapterSchedulerUtil.addJob(this.scheduler, info);
				} catch (Exception e) {
					logger.error("onApplicationEvent error :"+e.getMessage());
					//e.printStackTrace();
				}
			}
		}else if (arg0 instanceof org.springframework.context.event.ContextClosedEvent){
			HashMap<String, AdapterJobInfo> map =null;
			HashMap<String, Object> paramMap = new HashMap<String, Object>();
			try {
				map = spcfTmAdapterDao.getAdapterSchedule(paramMap);
			} catch (Exception e2) {
				//e2.printStackTrace();
				map = new HashMap<String, AdapterJobInfo>();
			}
			AdapterJobInfo info = null;		
			for(String key : map.keySet()) {
				info = map.get(key);
				try {
					AdapterSchedulerUtil.deleteJob(this.scheduler, info.getJobName());
				} catch (Exception e) {
					logger.error("onApplicationEvent error :"+e.getMessage());
					//e.printStackTrace();
				}
			}
		}else if (arg0 instanceof org.springframework.context.event.ContextStartedEvent){
		}else if (arg0 instanceof org.springframework.context.event.ContextStoppedEvent){
		}
		
	}



}
