package com.lanyuanxiaoyao.service.scheduler;

import cn.hutool.core.thread.ThreadUtil;
import com.lanyuanxiaoyao.service.scheduler.strategy.ScheduleStrategy;
import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
import org.eclipse.collections.api.list.ImmutableList;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;

/**
 * 启动类
 *
 * @author ZhangJiacheng
 * @date 2023-05-11
 */
@EnableDiscoveryClient
@SpringBootApplication(exclude = {GsonAutoConfiguration.class})
@ComponentScans({
        @ComponentScan("com.lanyuanxiaoyao.service"),
})
@EnableConfigurationProperties
@EnableEncryptableProperties
public class SchedulerApplication implements ApplicationRunner {
    private static final Logger logger = LoggerFactory.getLogger(SchedulerApplication.class);
    private final DiscoveryClient client;
    private final Scheduler quartzScheduler;
    private final ImmutableList<ScheduleStrategy> strategies;
    @Value("spring.application.name")
    private String application;

    public SchedulerApplication(DiscoveryClient client, Scheduler quartzScheduler, ImmutableList<ScheduleStrategy> strategies) {
        this.client = client;
        this.quartzScheduler = quartzScheduler;
        this.strategies = strategies;
    }

    public static void main(String[] args) {
        SpringApplication.run(SchedulerApplication.class, args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 队列不支持分布式启动，只能启动一个
        if (client.getServices().contains(application)) {
            logger.error("Found " + application + " exists, exit...");
            logger.warn("Wait for 15s and exit");
            ThreadUtil.safeSleep(15000);
            System.exit(1);
        }

        for (ScheduleStrategy strategy : strategies) {
            if (strategy.enable()) {
                logger.info("Schedule {} ({})", strategy.name(), strategy.comment());
                quartzScheduler.scheduleJob(strategy.job(), strategy.trigger());
            } else {
                logger.warn("Strategy {} ({}) is disabled", strategy.name(), strategy.comment());
            }
        }
    }
}
