package com.utic.center.utic.ptis.server.controller;

import com.utic.center.common.utils.LogUtils;
import com.utic.center.common.utils.TimeUtils;
import com.utic.center.utic.ptis.server.dto.BatchJobInfoDto;
import com.utic.center.utic.ptis.server.repository.ApplicationRepository;
import com.utic.center.utic.ptis.server.service.UticPtisServerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;

@Slf4j
@Controller
@RequiredArgsConstructor
public class UticPtisServerController {

    private final UticPtisServerService service;

    private String prevPrcsTime;
    private boolean isRunning = false;
    private int yesterday = 0; // 전일 일자
    private int today;
    private int minute;

    public boolean initialize() {
        LocalDateTime now = LocalDateTime.now();
        this.isRunning = false; // 현재 작업이 실행중이 아님을 표시
        this.yesterday = now.getDayOfMonth();  // 프로그램 기동시 오늘일자로 설정(다음날 부터 통계가 생성된다-통계생성시 통계일은 이전일)
        this.prevPrcsTime = "";

        return this.service.initialize();
    }

    private void calculateTime() {
        LocalDateTime now = LocalDateTime.now();
//        int year = now.getYear();
//        int month = now.getMonthValue();
        this.today = now.getDayOfMonth(); // 오늘 일자
        this.minute = now.getMinute();  // 현재 분
//        int hour = now.getHour();
//        int minute = now.getMinute();
//        int second = now.getSecond();
//        String nowTime = String.format("%04d%02d%02d%02d%02d%02d", year, month, day, hour, minute, second);
    }

    //@SchedulingElapsed(type="05MIN", name="PTIS ETLP Job Processing")
    public void run() {
        final long start = System.currentTimeMillis();
        calculateTime();
        if (this.yesterday != this.today) {
            //this.service.processDay(); // 일작업 수행
            this.yesterday = this.today; // 오늘 일자로 갱신
        }
        if (this.minute % 5 != 4) { // 5분마다 실행
            return;
        }

        log.info("");
        if (this.isRunning) {
            log.warn("[INF] {}: [{}] - Already running.", LogUtils.elapsedLog("Overlapping"), this.prevPrcsTime);
        }

        this.isRunning = true; // 현재 작업이 실행중임을 표시
        this.prevPrcsTime = TimeUtils.getCurrentTimeString(); // 현재 작업 시간 저장

        log.info("##>> 05MIN {}: [{}]", LogUtils.elapsedLog("PTIS ETLP Job Processing Start", 5), this.prevPrcsTime);

        BatchJobInfoDto jobInfo = new BatchJobInfoDto(TimeUtils.now());

        this.service.initIndigoStats();
        this.service.jobEtlpTraf();
        this.service.jobEtlpEvnt();
        this.service.jobEtlpIncd();
        this.service.insIndigoStats();
        this.service .jobDeleteTable();

        this.isRunning = false; // 현재 작업이 종료됨을 표시
        long executionTime = System.currentTimeMillis() - start;

        jobInfo.setEndTime(TimeUtils.now());
        jobInfo.setElapsedTime(executionTime);
        jobInfo.setTraf(this.service.getTraf());
        jobInfo.setEvnt(this.service.getEvnt());
        jobInfo.setIncd(this.service.getIncd());
        jobInfo.setTotTraf(ApplicationRepository.indigoStats.getTrafCnt());
        jobInfo.setTotEvnt(ApplicationRepository.indigoStats.getEvntCnt());
        jobInfo.setTotIncd(ApplicationRepository.indigoStats.getIncdCnt());
        jobInfo.setTrafDate(ApplicationRepository.lastRegDate.getTrafDt());
        jobInfo.setEvntDate(ApplicationRepository.lastRegDate.getEvntDt());
        jobInfo.setIncdDate(ApplicationRepository.lastRegDate.getIncdDt());
        ApplicationRepository.addJobInfo(jobInfo);

        log.info("[INF] {}: Update, TRAF: {}/{}, EVNT: {}/{}, INCD: {}/{}",
                LogUtils.elapsedLog("INDIGO_STATUS"),
                this.service.getTraf(), ApplicationRepository.indigoStats.getTrafCnt(),
                this.service.getEvnt(), ApplicationRepository.indigoStats.getEvntCnt(),
                this.service.getIncd(), ApplicationRepository.indigoStats.getIncdCnt());

        log.info("<<## 05MIN {} [{}], {} ms.", LogUtils.elapsedLog("PTIS ETLP Job Processing End", 5, executionTime),
                this.prevPrcsTime, executionTime);
    }
}
