package com.blueland.config.quartz.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.apache.commons.lang3.StringUtils;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.blueland.config.CustomConfig;
import com.blueland.config.quartz.service.ScheduleServiceI;

import lombok.extern.slf4j.Slf4j;

/**
* @author zhengTao
* @version 创建时间：2019年4月26日 下午8:02:14
   * 定时任务扫描Listener
*/
@WebListener
@Slf4j
public class TaskStartListener implements ServletContextListener {
 
    private ScheduleServiceI scheduleService;
    @Autowired
	CustomConfig customConfig;
 
    private static final String SCHEDULE_SERVICE_NAME = "scheduleService";
    private static final String SCHEDULER_NAME = "scheduler";
 
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    	log.info("TaskStartListener contextDestroyed");
    }
 
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        try {
        	log.info("TaskStartListener contextInitialized");
            this.initial(servletContextEvent);
        } catch (Exception ex) {
            log.error(ex.getMessage());
            ex.printStackTrace();
        }
    }
 
    /**
     * 用来启动定时器的
     * @param servletContextEvent
     */
    private void initial(ServletContextEvent servletContextEvent) {
        Boolean isScan;
//        if (StringUtils.isEmpty(customConfig.getQuartzScan())) {
//            isScan = true;
//        } else {
//            isScan = Boolean.parseBoolean(customConfig.getQuartzScan());
//        }
        isScan = true;
        if (isScan) {
            ServletContext context = servletContextEvent.getServletContext();
            ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(context);
            this.scheduleService = (ScheduleServiceI) applicationContext.getBean(SCHEDULE_SERVICE_NAME);
            Scheduler scheduler = (Scheduler) applicationContext.getBean(SCHEDULER_NAME);
            this.scheduleService.setScheduler(scheduler);
            this.scheduleService.proceedSchedule();
        }
    }
 
}
