package com.nokia.alarm.config;

import java.util.Date;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import com.nokia.alarm.service.AlarmSaveToFileService;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
public class SchedulingConfig implements SchedulingConfigurer {

    @Value("${scheduling.scheduler.pool.size:1}")
    private int poolSize;

    private final AlarmSaveToFileService service;

    public SchedulingConfig(AlarmSaveToFileService service) {
        this.service = service;
    }

    @Bean
    public ThreadPoolTaskScheduler taskScheduler() {
        // 使用最常用的ThreadPoolTaskScheduler
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        // 线程数
        taskScheduler.setPoolSize(poolSize);
        taskScheduler.setRemoveOnCancelPolicy(true);
        taskScheduler.setThreadNamePrefix("taskSchedulerThreadPool-");
        log.info("已完成 ThreadPoolTaskScheduler 配置, poolSize = {}", poolSize);
        return taskScheduler;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskScheduler());
        taskRegistrar.addCronTask(() -> {
            Date date = new Date();
            try {
                service.getHttpSave(date);
                service.getHttpUpdate(date);
            } catch (Exception e) {
                e.printStackTrace();
                // 延时 2 分钟重新调度一下
                Date newDate = new Date(date.getTime() + 2 * 60000);
                taskRegistrar.getScheduler().schedule(() -> {
                    service.getHttpSave(newDate);
                    service.getHttpUpdate(newDate);
                }, newDate);
            }
        }, "0 */5 * * * ?");
    }

}
