package com.tsi.api.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 TsiSchedulingConfig implements SchedulingConfigurer {

    private int poolCore = 0;

    private final int SCHEDULE_THREAD_POOL_SIZE = 10;

    @PostConstruct
    private void init() {
        log.info("[{}] ------------", this.getClass().getSimpleName());
        if (this.poolCore == 0) {
            log.info("[{}] poolCore size set as default: {} EA.", this.getClass().getSimpleName(), this.poolCore);
            this.poolCore = 10;
        }
        log.info("[{}] poolCore: {} EA.", this.getClass().getSimpleName(), this.poolCore);
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {

        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();

        threadPoolTaskScheduler.setPoolSize(SCHEDULE_THREAD_POOL_SIZE);
        threadPoolTaskScheduler.setThreadNamePrefix("scheduler-");
        threadPoolTaskScheduler.initialize();

        scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
    }
}
