package com.its.app.scheduler;

import com.its.app.config.ServerConfig;
import com.its.app.service.CctvService;
import com.its.app.service.UnitSystService;
import com.its.app.service.WcamService;
import com.its.utils.Elapsed;
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
@EnableScheduling
@Component("schedulerTask")
public class SchedulerTask {

    private final ServerConfig serverConfig;
    private final UnitSystService unitSystService;
    private final WcamService wcamService;
    private final CctvService cctvService;

    public SchedulerTask(ServerConfig serverConfig, UnitSystService unitSystService, WcamService wcamService, CctvService cctvService) {
        this.serverConfig = serverConfig;
        this.unitSystService = unitSystService;
        this.wcamService = wcamService;
        this.cctvService = cctvService;
    }

    //@Scheduled(cron = "*/10 * * * * *") //==> 10초마다 실행
    @Scheduled(cron = "2 * * * * ?")  // 1분주기 작업 실행
    public void UnitSystSchedule() {
        if (!this.serverConfig.isStartSchedule()) {
            return;
        }
        Elapsed elapsed = new Elapsed();
        log.info("UnitSystSchedule :: start. {}", Thread.currentThread().getName());

        // 1. 프로세스 상태정보 업데이트
        this.unitSystService.updateUnitSyst(true);

        log.info("UnitSystSchedule :: ..end. {} ms. {}", elapsed.milliSeconds(), Thread.currentThread().getName());
    }

    @Scheduled(cron = "${wcam.crontab:0 10 * * * *}")
    public void WcamSchedule() {
        if (!this.serverConfig.isStartSchedule()) {
            return;
        }
        Elapsed elapsed = new Elapsed();
        log.info("WcamSchedule :: start. {}", Thread.currentThread().getName());
        this.wcamService.doJob();
        log.info("WcamSchedule :: ..end. {} ms. {}", elapsed.milliSeconds(), Thread.currentThread().getName());
    }

    @Scheduled(cron = "${cctv.crontab:0 15 * * * *}")
    public void CctvSchedule() {
        if (!this.serverConfig.isStartSchedule()) {
            return;
        }
        Elapsed elapsed = new Elapsed();
        log.info("CctvSchedule :: start. {}", Thread.currentThread().getName());
        this.cctvService.doJob();
        log.info("CctvSchedule :: ..end. {} ms. {}", elapsed.milliSeconds(), Thread.currentThread().getName());
    }

    @PreDestroy
    public void onShutDown() {
        this.unitSystService.updateUnitSyst(false);
        log.info("onShutDown updateUnitSyst");
    }
}
