package com.tsi.comm.server.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
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 javax.annotation.PostConstruct;

@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "application.scheduling")
public class SchedulingConfig implements SchedulingConfigurer {

    private int poolSize = 0;

    private final int SCHEDULE_THREAD_POOL_SIZE = 10;

    @PostConstruct
    private void init() {
        if (this.poolSize < this.SCHEDULE_THREAD_POOL_SIZE) {
            this.poolSize = this.SCHEDULE_THREAD_POOL_SIZE;
        }
        log.info("[SchedulingConfig] ------------");
        log.info("[SchedulingConfig] poolCore: {} EA.", this.poolSize);
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {

        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();

        threadPoolTaskScheduler.setPoolSize(this.poolSize);
        threadPoolTaskScheduler.setThreadNamePrefix("tsi-scheduler-");
        threadPoolTaskScheduler.initialize();

        scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
    }
}
