// let webSocket = new SockJS("http://"+window.location.host+"/allTopic.do");
//let webSocket = new SockJS("http://"+window.location.hostname+":8443/allTopic.do");
//let webSocket = new SockJS("https://"+window.location.hostname+":7443/allTopic.do");
//let webSocket = new SockJS("https://192.168.20.15:7443/allTopic.do");
// let webSocket = connectWebSocket();
let _CvibNodeArr = [];
let tempNodeArr = [];
let _CvibNodeBotListArr = [];
let reconnectAttempts = 0;
let _Interval = null;
function getCvibList() {
    let start = new Date().getTime();
    if (_Interval) clearTimeout(_Interval);
    const minX = map.getBounds().getSouthWest().getLng();
    const minY = map.getBounds().getSouthWest().getLat();
    const maxX =map.getBounds().getNorthEast().getLng();
    const maxY = map.getBounds().getNorthEast().getLat();
    const token = $("meta[name='_csrf']").attr("content");
    const header = $("meta[name='_csrf_header']").attr("content");
    $.ajax({
        method: 'POST',
        url : '/getCvibList.do',
        beforeSend: (xhr) => {
            xhr.setRequestHeader(header, token)
        },
        data : {
            minX : minX,
            minY : minY,
            maxX : maxX,
            maxY : maxY,
        },
        success: (res) => {
            recvCvibListData(res);
            let end = new Date().getTime();
            let differ = end - start;
            // console.log('소요시간 :',differ, 'ms');
            if ((differ) >= 1000) {
                differ = 1000;
            }
            _Interval = setTimeout(getCvibList, 1000 - differ);
        },
        error: (err) => {
            console.log(err);
        }
    })
}


$(()=>{
    getCvibList();
})

function recvCvibListData(recv) {
    if (!recv || recv.length === 0) return;
    const {sectionList, statusList} = recv;

    let cvibSttsDefault = [];
    for (let i = 10; i <= 80; i = i + 10) {
        cvibSttsDefault[i] = '9_9_9_9';
    }

    if (_Level < 9) {
        for (let ii = 0; ii < sectionList.length; ii++) {
            let light       = []			// 신호등정보 [직진,좌,보행]
            let dirAdd      = [];			//연등지
            let timeFlag    = [];			//시간정보신뢰성
            let walker      = [];			//보행자
            let unprotected = [];			//비보호 상태
            let stts        = [];			//신호등상태
            let dispTm      = [];			//표출시간
            let remainTm    = [];			//잔여시간
            let dirCode     = []; 			//방향코드
            let cvibSttsArr = [...cvibSttsDefault];
           // 직진_좌회전_보행_유턴
            let nodeId      = sectionList[ii].nodeId;
            let localDate   = sectionList[ii].localDate;
            let dataCount   = sectionList[ii].dataCount;
            let counter     = sectionList[ii].counter;
            // let connDate    = sectionList[ii].connDate;
            let errCenter   = transStatusCodeToWord(sectionList[ii].errCenter, 0);
            let errCont     = transStatusCodeToWord(sectionList[ii].errCont, 0);
            let errScu      = transStatusCodeToWord(sectionList[ii].errScu, 0);
            let oprBlink    = transStatusCodeToWord(sectionList[ii].oprBlink, 1);
            let oprTrans    = transStatusCodeToWord(sectionList[ii].oprTrans, 1);
            let oprInd      = transStatusCodeToWord(sectionList[ii].oprInd, 1);
            let oprManual   = transStatusCodeToWord(sectionList[ii].oprManual, 1);
            let oprTurnoff  = transStatusCodeToWord(sectionList[ii].oprTurnoff, 1);

            if (sectionList[ii].turns.length > 0) {
                sectionList[ii].turns.sort(dirCodeSort);
                for (let turn of sectionList[ii].turns) {
                    stts.push(turn.stts)
                    light.push(turn.light);
                    dirAdd.push(turn.dirAdd);
                    timeFlag.push(turn.timeFlag);
                    walker.push(turn.walker);
                    unprotected.push(turn.unprotected);
                    dispTm.push(turn.dispTm);
                    remainTm.push(turn.remainTm);
                    dirCode.push(turn.dirCode);
                    cvibSttsArr[turn.dirCode] = setCvibSttsFnc(turn.unprotected, turn.light, turn.dirCode, turn.stts, cvibSttsArr[turn.dirCode]);
                }
            }

            let sigIdx = signalArr.findIndex(signal => signal.nodeId == nodeId);
            if (sigIdx >= 0) {
                const signal = signalArr[sigIdx];
                const cvib   = new CvibInfo(signal.nodeId, signal.name, signal.Lat, signal.Lng, signal.addr1,
                    signal.addr2, signal.addr3, localDate, errCenter, errCont, errScu, oprBlink, oprInd, oprManual, oprTrans, oprTurnoff, dataCount, counter,
                    cvibSttsArr[10], cvibSttsArr[20], cvibSttsArr[30], cvibSttsArr[40], cvibSttsArr[50], cvibSttsArr[60], cvibSttsArr[70], cvibSttsArr[80],
                    light, dirAdd, timeFlag, walker, unprotected, stts, dispTm, remainTm, dirCode);

                if (_CvibNodeArr.length === 0) {
                    _CvibNodeArr.push(cvib);
                }
                else {
                    let findIdx = _CvibNodeArr.findIndex(cvibNode => cvibNode.nodeId == nodeId);
                    if (findIdx >= 0) {
                        _CvibNodeArr[findIdx] = cvib;
                    }
                    else {
                        _CvibNodeArr.push(cvib);
                    }
                }
            }

            if(_Level === 0 || _Level === 1){
                _CvibNodeArr.forEach(function (el) {
                    for (let ii = 0; ii < signalArr.length; ii++) {
                        if(el.nodeId == signalArr[ii].nodeId){
                            el.emptyCvibCircleImg();
                            el.emptyCvibInfoImg();
                        }
                    }
                });
                _CvibNodeArr.forEach(function (el) {
                    for (let ii = 0; ii < signalArr.length; ii++) {
                        if(el.nodeId == signalArr[ii].nodeId){
                            //console.log(el.nodeId + " 셋팅");
                            el.setCircle();
                            el.setCvibInfo();
                        }
                    }

                });
            }
            const $nodeEl = $('#cvibBottomBodyTable').find('#' + nodeId);
            $nodeEl.find('#oprTrans').empty().text(oprTrans);
            $nodeEl.find('#oprInd').empty().text(oprInd);
            $nodeEl.find('#oprTurnoff').empty().text(oprTurnoff);
            $nodeEl.find('#oprBlink').empty().text(oprBlink);
            $nodeEl.find('#oprManual').empty().text(oprManual);
            $nodeEl.find('#errScu').empty().text(errScu);
            $nodeEl.find('#errCenter').empty().text(errCenter);
            $nodeEl.find('#errCont').empty().text(errCont);
            $nodeEl.find('#counter').empty().text(counter);
            $nodeEl.find('#date').empty().text(localDate);
        }

        for (let status of statusList) {
            let idx = _signalInfoArr.findIndex(obj => obj.nodeId == status.nodeId);
            if (idx >= 0) {
                _signalInfoArr[idx].date = status.date;
                _signalInfoArr[idx].connDate = status.connDate;
                _signalInfoArr[idx].commStatus = status.commStatus;
            }
        }
    }
}

function transStatusCodeToWord(value, option) {
    const wordArr = [['정상', '이상', '-'], ['OFF', 'ON', '-']];
    if (value !== undefined && !isNaN(Number(value))) {
        return wordArr[option][value];
    }
    return wordArr[option][2];
}

function setCvibSttsFnc(unprotected, light, dirCode, stts, cvibStts) {
    if (cvibStts === undefined || cvibStts === "" || cvibStts === null) {
        //TODO: 20230221
        cvibStts = '9_9_9_9';
    }
    if (light === 1) {
        let temp = cvibStts.substring(1);
        cvibStts = stts + temp;
    } else if (light === 2) {
        let tempS = cvibStts.substring(0, 2);
        let tempE = cvibStts.substring(3);
        //stts =(unprotected == 0) ? stts : 1;
        cvibStts = tempS + stts + tempE;
    } else if (light === 3) {
        let tempS = cvibStts.substring(0, 4);
        let tempE = cvibStts.substring(5);
        cvibStts = tempS + stts + tempE;
    } else if (light === 7) {
        let temp = cvibStts.substring(0, 6);
        cvibStts = temp + stts;
    }
    return cvibStts;
}

function dirCodeSort(a, b) {
    return a.dirCode - b.dirCode;
}

/*
	시간 포멧 변경 함수
	format('yyyy-MM-dd')
	format('HH:mm:ss')
	format('yyyy-MM-dd(KS) HH:mm:ss')
	format('yyyy-MM-dd a/p hh:mm:ss')
 */
Date.prototype.format = function (f) {

    if (!this.valueOf()) return " ";


    let weekKorName = ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"];

    let weekKorShortName = ["일", "월", "화", "수", "목", "금", "토"];

    let weekEngName = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    let weekEngShortName = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

    let d = this;


    return f.replace(/(yyyy|yy|MM|dd|KS|KL|ES|EL|HH|hh|mm|ss|a\/p)/gi, function ($1) {

        switch ($1) {

            case "yyyy":
                return d.getFullYear(); // 년 (4자리)

            case "yy":
                return (d.getFullYear() % 1000).zf(2); // 년 (2자리)

            case "MM":
                return (d.getMonth() + 1).zf(2); // 월 (2자리)

            case "dd":
                return d.getDate().zf(2); // 일 (2자리)

            case "KS":
                return weekKorShortName[d.getDay()]; // 요일 (짧은 한글)

            case "KL":
                return weekKorName[d.getDay()]; // 요일 (긴 한글)

            case "ES":
                return weekEngShortName[d.getDay()]; // 요일 (짧은 영어)

            case "EL":
                return weekEngName[d.getDay()]; // 요일 (긴 영어)

            case "HH":
                return d.getHours().zf(2); // 시간 (24시간 기준, 2자리)

            case "hh":
                return ((h = d.getHours() % 12) ? h : 12).zf(2); // 시간 (12시간 기준, 2자리)

            case "mm":
                return d.getMinutes().zf(2); // 분 (2자리)

            case "ss":
                return d.getSeconds().zf(2); // 초 (2자리)

            case "a/p":
                return d.getHours() < 12 ? "오전" : "오후"; // 오전/오후 구분

            default:
                return $1;

        }

    });

};

String.prototype.string = function (len) {
    let s = '', i = 0;
    while (i++ < len) {
        s += this;
    }
    return s;
};

String.prototype.zf = function (len) {
    return "0".string(len - this.length) + this;
};

Number.prototype.zf = function (len) {
    return this.toString().zf(len);
};