package com.its.api.scheduler.job;

import com.its.api.its.model.dto.cctv.TbCctvScnrDto;
import com.its.api.its.model.entity.cctv.TbCctvScnr;
import com.its.api.its.repository.cctv.TbCctvScnrRepository;
import com.its.api.utils.ItsUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@AllArgsConstructor
@Service
public class CctvPsetScnrJobThread {

    private final TbCctvScnrRepository cctvScnrRepo;

    @Async("cctvPsetScnrExecutor")
    public void run() {

        log.info("START: CctvPsetScnrThread.run: {}", Thread.currentThread().getName());

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        List<TbCctvScnrDto> cctvScnrList = new ArrayList<>();
        List<TbCctvScnr> cctvScnr = this.cctvScnrRepo.findAllList();
        cctvScnr.forEach(obj -> {
            cctvScnrList.add(obj.toDto());
        });

        String currDay = ItsUtils.getSysTime("yyyyMMdd");
        String currCtrlDt = currDay+ItsUtils.getSysTime("HHmm");

        cctvScnrList.forEach(obj -> {

            String controlDt = currDay + obj.getStrtHms().substring(0, 4);
            int scheduleMin = ItsUtils.getDiffMinutes(controlDt+"00", currCtrlDt+"00");
            if (scheduleMin < 0 || scheduleMin > 2) {
                return;
            }

            // 제어시각 = 제어시작시각+0,1,2(분)
            if (obj.getCtrlDt() != null && currCtrlDt.equals(obj.getCtrlDt().substring(0, 12))) {
                if (("Y").equals(obj.getCtrlResYn())) {
                    // 이미 제어를 수행하였고 결과가 성공이었다면 다시 제어할 필요 없음
                    return;
                }
            }

            // 제어를 시작한다.
log.error("Control: {}, {}, {}, {}", obj.getCctvMngmNmbr(), obj.getStrtHms(), obj.getPsetNmbr(), currCtrlDt);

            TbCctvScnr scnr = TbCctvScnr.builder()
                    .cctvMngmNmbr(obj.getCctvMngmNmbr())
                    .strtHms(obj.getStrtHms())
                    .endHms(obj.getEndHms())
                    .psetNmbr(obj.getPsetNmbr())
                    .ctrlDt(controlDt+"00")
                    .ctrlResYn("N")
                    .build();
            //this.cctvScnrRepo.(scnr);
            String ctrlResYn = "N";
            if (obj.getCctvMngmNmbr() % 2 == 0) {
                ctrlResYn = "Y";
            }
            this.cctvScnrRepo.updateResult(obj.getCctvMngmNmbr(), obj.getStrtHms(), obj.getEndHms(), controlDt+"00", ctrlResYn);
        });

        stopWatch.stop();
        log.info("--END: CctvPsetScnrThread.run: {}, {} ms.", Thread.currentThread().getName(), stopWatch.getTotalTimeMillis());
    }
}
