package com.utic.center.utic.traf.server.scheduler;

import com.utic.center.utic.traf.server.config.ApplicationConfig;
import com.utic.center.utic.traf.server.config.TraceConfig;
import com.utic.center.utic.traf.server.controller.UticTrafServerController;
import com.utic.center.utic.traf.server.service.ProcessStateService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@RequiredArgsConstructor
@EnableScheduling
@Component
public class UticTrafServerScheduler {

    private final ApplicationConfig config;
    private final TraceConfig traceConfig;
    private final ProcessStateService processStateService;
    private final UticTrafServerController controller;

    @Async
    @Scheduled(cron = "1 4/5 * * * *")  // 5분주기 작업 실행
    public void scheduleTrace() {
        try {
            this.traceConfig.loadTraceInfo();
        } catch(Exception e) {
            log.error("UticTrafServerScheduler.scheduleTrace: Exception {}", e.getMessage());
        }
    }

    @Scheduled(cron = "0 * * * * *")
    public void scheduleProcess() {
        if (this.config.isStartSchedule()) {
            try {
                this.controller.run();
            } catch (Exception e) {
                log.error("UticTrafServerScheduler.scheduleProcess: Exception {}", e.getMessage());
            }

            try {
                // 프로세스 상태정보 업데이트
                this.processStateService.processRunning();
            } catch(Exception e) {
                log.error("UticTrafServerScheduler.updateProcessState: Exception {}", e.getMessage());
            }
        }
    }

}
