package com.bonus.tcp.task.config;


import com.bonus.tcp.task.service.ScheduleService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;

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

/**
 * 定时任务扫描Listener
 * moss
 */
@Component
@Slf4j
@WebListener
@Configuration
public class StartupListener implements ServletContextListener {




    private ScheduleService scheduleService;

    private static final String SCHEDULE_SERVICE_NAME = "scheduleService";

    private static final String SCHEDULER_NAME = "scheduler";

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }


    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        try {
            this.initial(servletContextEvent);
        } catch (Exception ex) {
            log.error(ex.getMessage());
            ex.printStackTrace();
        }
    }
    /**
     * 用来启动定时器的
     *
     * @param servletContextEvent
     */
    private void initial(ServletContextEvent servletContextEvent) {
        ServletContext context = servletContextEvent.getServletContext();
        ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(context);
        this.scheduleService = (ScheduleService) applicationContext.getBean(SCHEDULE_SERVICE_NAME);
        Scheduler scheduler = (Scheduler) applicationContext.getBean(SCHEDULER_NAME);
        this.scheduleService.setScheduler(scheduler);
        this.scheduleService.proceedSchedule();
    }


}