package com.its.app.thread;

import com.its.app.config.AppUtils;
import com.its.app.process.DbmsJobData;
import com.its.app.process.DbmsJobProcess;
import com.its.app.process.DbmsJobType;
import com.its.app.vo.voIcmpCtlr;
import com.its.app.vo.voIcmpCtlrStts;
import com.its.utils.Ping;
import com.its.utils.SysUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Slf4j
@Service("icmpPingThread")
public class IcmpPingThread {

    @Value("${icmp.ping.timeout:#{5}}")
    private int pingTimeout;

    @Async("icmpPingExecutor")
    public void run(int type, boolean isHistory, String UPDT_DT, voIcmpCtlr obj) {

        String keyData = "wcam";
        if (type == DbmsJobType.DATA_TYPE_CCTV_STTS) {
            keyData = "cctv";
        }
        MDC.put("id", keyData);

        voIcmpCtlrStts stts = new voIcmpCtlrStts();
        stts.setCTLR_NMBR(obj.getCTLR_NMBR());
        stts.setUPDT_DT(UPDT_DT);
        stts.setCMNC_STTS_CD("CMS1");   // 비정상으로 기본 설정

        boolean isReachable = false;
        long startTm = System.nanoTime();
        long endTm = System.nanoTime();
        log.info("{}, {}, {}, {}, app try. timeout: {} sec. {}", keyData, obj.getCTLR_NMBR(), obj.getISTL_LCTN_NM(), obj.getCTLR_IP(),
                this.pingTimeout, Thread.currentThread().getName());
        try {
            isReachable = Ping.isReachable(obj.getCTLR_IP(), this.pingTimeout);
            endTm = System.nanoTime();
            if (isReachable ) {
                stts.setCMNC_STTS_CD("CMS0");
                log.info("{}, {}, {}, {}, is alive. {} ms.", keyData, obj.getCTLR_NMBR(), obj.getISTL_LCTN_NM(), obj.getCTLR_IP(), (endTm - startTm) / 1000000);
            }
            else {
                log.error("{}, {}, {}, {}, is not alive. {} ms.", keyData, obj.getCTLR_NMBR(), obj.getISTL_LCTN_NM(), obj.getCTLR_IP(), (endTm - startTm) / 1000000);
            }
        }
        catch (Exception e) {
            log.error("{}, {}, {}, {}, Exception: {}", keyData, obj.getCTLR_NMBR(), obj.getISTL_LCTN_NM(), obj.getCTLR_IP(), e.toString());
        }

        if (isReachable) {
            obj.setNetState(1);
        }
        else {
            obj.setNetState(0);
        }
        obj.setReachable(isReachable);
        obj.setPingTime(SysUtils.getSysTimeStr());

        DbmsJobProcess icmpPingDataProcess = (DbmsJobProcess) AppUtils.getBean(DbmsJobProcess.class);
        icmpPingDataProcess.add(new DbmsJobData(type, false, stts));
        if (isHistory) {
            icmpPingDataProcess.add(new DbmsJobData(type, true, stts));
        }

        MDC.remove(keyData);
        MDC.clear();
    }

}
