package com.njzscloud.common.sichen.config;

import com.njzscloud.common.core.thread.ThreadPool;
import com.njzscloud.common.sichen.SysTaskService;
import com.njzscloud.common.sichen.dispatcher.SichenScheduler;
import com.njzscloud.common.sichen.executor.SichenExecutor;
import com.njzscloud.common.sichen.support.TaskStore;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
@MapperScan("com.njzscloud.common.sichen")
@EnableConfigurationProperties(TaskProperties.class)
public class TaskAutoConfiguration {

    @Bean
    public SysTaskService sysTaskService() {
        return new SysTaskService();
    }

    @Bean
    public TaskStore taskStore(SysTaskService sysTaskService) {
        return new TaskStore(sysTaskService);
    }

    @Bean(destroyMethod = "stop")
    public SichenExecutor sichenExecutor(TaskProperties taskProperties) {
        TaskProperties.Pool pool = taskProperties.getPool();
        return new SichenExecutor(ThreadPool.createThreadPool(
                pool.getPoolName(),
                pool.getCorePoolSize(),
                pool.getMaxPoolSize(),
                pool.getKeepAliveSeconds(),
                pool.getWindowCapacity(),
                pool.getStandbyCapacity(),
                (r, p) -> log.error("任务执行器线程池已满，拒绝任务：{}", r.toString())
        ));
    }

    @Bean(destroyMethod = "stop")
    public SichenScheduler sichenScheduler(TaskStore taskStore) {
        return new SichenScheduler(taskStore);
    }


}
