package com.hs.admin.config;

import com.hs.admin.factory.JobFactory;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.io.IOException;
import java.util.Properties;


/**
 * @author xieheng
 */
@Configuration
public class QuartzConfigration {
    private static final Logger LOGGER = LoggerFactory.getLogger(QuartzConfigration.class);
    @Autowired
    JobFactory jobFactory;

    /**
     * @description: 配置bean
     * @return: SchedulerFactoryBean
     * @author: XieHeng
     * @date: 2021/4/27 2:04 下午
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        try {
            schedulerFactoryBean.setOverwriteExistingJobs(true);
            schedulerFactoryBean.setQuartzProperties(getQuartzProperties());
            schedulerFactoryBean.setJobFactory(jobFactory);
        } catch (Exception e) {
            LOGGER.error(">>>QuartzConfigration配置失败：" + e);
        }
        return schedulerFactoryBean;
    }

    /**
     * @description: 指定配置文件，在配置文件中配置相关属性(quartz.properties在resource根目录下)
     * @return: Properties
     * @author: XieHeng
     * @date: 2021/4/27 2:05 下午
     */
    private Properties getQuartzProperties() {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        ClassPathResource resource = new ClassPathResource("/quartz.properties");
        Properties properties = null;
        propertiesFactoryBean.setLocation(resource);
        try {
            propertiesFactoryBean.afterPropertiesSet();
            properties = propertiesFactoryBean.getObject();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties;
    }

    /**
     * @description: 获取scheduler
     * @return: Scheduler
     * @author: XieHeng
     * @date: 2021/4/27 2:12 下午
     */
    @Bean(name = "scheduler")
    public Scheduler scheduler() {
        return schedulerFactoryBean().getScheduler();
    }

}
