package com.its.vds.scheduler;

import com.its.app.AppUtils;
import com.its.app.utils.Elapsed;
import com.its.vds.config.ApplicationConfig;
import com.its.vds.config.DebugConfig;
import com.its.vds.service.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

@Slf4j
@AllArgsConstructor
@EnableScheduling
@Component
public class SchedulerTask {

    private final ApplicationConfig config;
    private final UnitSystService unitSystService;
    private final VdsCtlrService vdsCtlrService;
    private final AppRepositoryService repoService;

    @PreDestroy
    public void onShutDown() {
         this.unitSystService.updateUnitSystStts(false);
        DebugConfig debug = (DebugConfig) AppUtils.getBean(DebugConfig.class);
        debug.saveDebugInfo();
    }

    @Scheduled(cron = "5 * * * * *")  // 1분주기 작업 실행
    public void scheduleUnitSystStts() {
        if (!this.config.isStartSchedule()) {
            return;
        }
        Elapsed elapsed = new Elapsed();
        log.info("scheduleUnitSystStts: start. {}", Thread.currentThread().getName());
        // 1. 프로세스 상태정보 업데이트
        this.unitSystService.updateUnitSystStts(true);
        // 2. 제어기 상태정보 업데이트
        this.vdsCtlrService.updateCtlrStts(true, null);
        log.info("scheduleUnitSystStts: ..end. {} ms. {}", elapsed.milliSeconds(), Thread.currentThread().getName());
    }

    @Scheduled(cron = "8 * * * * *")  // 1분주기 작업 실행
    public void scheduleVdsStatusRequest() {
        if (!this.config.isStartSchedule()) {
            return;
        }
        Elapsed elapsed = new Elapsed();
        log.info("scheduleVdsStatusRequest: start. {}", Thread.currentThread().getName());
        log.info("scheduleVdsStatusRequest: ..end. {} ms. {}", elapsed.milliSeconds(), Thread.currentThread().getName());
    }

    @Scheduled(cron = "30 0/5 * * * *")    // 정주기 5분 30초에 스케쥴 실행
    public void schedule5M() {
        if (!this.config.isStartSchedule()) {
            return;
        }
        Elapsed elapsed = new Elapsed();
        log.info("schedule5M..: start. {}", Thread.currentThread().getName());
        log.info("schedule5M..: ..end. {} ms. {}", elapsed.milliSeconds(), Thread.currentThread().getName());
    }

    @Scheduled(cron = "10 3,8,13,18,23,28,33,38,43,48,53,58 * * * *")  // 5분주기 작업 실행
    public void scheduleVdsDnldSymb() {
        if (!this.config.isStartSchedule()) {
            return;
        }
        Elapsed elapsed = new Elapsed();
        log.info("scheduleVdsDnldSymb: start. {}", Thread.currentThread().getName());
        log.info("scheduleVdsDnldSymb: ..end. {} ms. {}", elapsed.milliSeconds(), Thread.currentThread().getName());
    }

}
