var webSocket = new SockJS("http://"+window.location.host+"/allTopic.do");
//var webSocket = new SockJS("http://"+window.location.hostname+":8443/allTopic.do");
//var webSocket = new SockJS("https://"+window.location.hostname+":7443/allTopic.do");
//var webSocket = new SockJS("https://192.168.20.15:7443/allTopic.do");

var _CvibNodeArr = [];
var tempNodeArr = [];
var _CvibNodeBotListArr = [];


webSocket.onopen = function (message) {
    wsOpen(message);
}
webSocket.onmessage = function (message) {
    wsOnMessage(message);
}
webSocket.onclose = function (message) {
    wsClose(message);
}
webSocket.onerror = function (message) {
    wsError(message);
}


function wsOpen(message) {
    console.log('wsOpen!');
    //wsSendMessage(message);
};

function wsCloseConnection() {
    console.log('close!');
    webSocket.close();
};

function wsOnMessage(message) {
    //_CvibNodeArr = [];
    //if(_CvibNodeArr.length> 50)_CvibNodeArr=[];
    var recv = JSON.parse(message.data);
    recv.sort(dirCodeSort);
    //console.log(recv);

    var nodeId;
    var date;
    var errCenter;
    var errCont;
    var errScu;
    var oprBlink;
    var oprInd;
    var oprManual;
    var oprTrans;
    var oprTurnoff;
    var dataCount;
    var counter;
    var connDate;

    var light = []			// 신호등정보 [직진,좌,보행]
    var dirAdd = [];			//연등지
    var timeFlag = [];			//시간정보신뢰성
    var walker = [];			//보행자
    var unprotected = [];			//비보호 상태
    var stts = [];			//신호등상태
    var dispTm = [];						//표출시간
    var remainTm = [];						//잔여시간
    var dirCode = []; 						//방향코드

    var cvibSttsArr = [];
    for (var i = 10; i <= 80; i = i + 10) {
        cvibSttsArr[i] = '9_9_9_9';
    } // 직진_좌회전_보행_유턴

    if (_Level < 9) {
        for (var ii = 0; ii < recv.length; ii++) {
            if (ii == 0) {
                nodeId = recv[ii].nodeId;
                date = recv[ii].date;
                dataCount = recv[ii].dataCount;
                counter = recv[ii].counter;
                connDate = recv[ii].connDate;

                (recv[ii].errCenter == 0) ? errCenter = '정상' : errCenter = '이상';
                (recv[ii].errCont == 0) ? errCont = '정상' : errCont = '이상';
                (recv[ii].errScu == 0) ? errScu = '정상' : errScu = '이상';

                (recv[ii].oprBlink == 0) ? oprBlink = 'OFF' : oprBlink = 'ON';
                (recv[ii].oprTrans == 0) ? oprTrans = 'OFF' : oprTrans = 'ON';
                (recv[ii].oprInd == 0) ? oprInd = 'OFF' : oprInd = 'ON';
                (recv[ii].oprManual == 0) ? oprManual = 'OFF' : oprManual = 'ON';
                (recv[ii].oprTurnoff == 0) ? oprTurnoff = 'OFF' : oprTurnoff = 'ON';

                continue;
            }

            //( recv[ii].light == 2 && recv[ii].stts == 3 && recv[ii].unprotected == 1 ) ? stts.push(1) : stts.push(recv[ii].stts);
            stts.push(recv[ii].stts)
            light.push(recv[ii].light);
            dirAdd.push(recv[ii].dirAdd);
            timeFlag.push(recv[ii].timeFlag);
            walker.push(recv[ii].walker);
            unprotected.push(recv[ii].unprotected);
            dispTm.push(recv[ii].dispTm);
            remainTm.push(recv[ii].remainTm);
            dirCode.push(recv[ii].dirCode);

            cvibSttsArr[recv[ii].dirCode] = setCvibSttsFnc(recv[ii].unprotected, recv[ii].light, recv[ii].dirCode, recv[ii].stts, cvibSttsArr[recv[ii].dirCode]);
        }

        for (var ii = 0; ii < signalArr.length; ii++) {

            if (recv[0].nodeId != signalArr[ii].nodeId) continue; //온 노드아이디랑 맵에있는 노드아이디랑 같은거만

            if(_CvibNodeArr.length < 1 ){  // 데이터가 없으면 새로 넣어주고
                _CvibNodeArr.push(new CvibInfo(signalArr[ii].nodeId, signalArr[ii].name, signalArr[ii].Lat, signalArr[ii].Lng, signalArr[ii].addr1,
                    signalArr[ii].addr2, signalArr[ii].addr3, date, 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));
            } else { //데이터가있으면
                // 소켓으로온 데이터가 있으면 바꿔주고
                var findFlag = _CvibNodeArr.find(function (el) {
                    if(el.nodeId == recv[0].nodeId) return true;
                });
                if(findFlag){
                    _CvibNodeArr.forEach(function(el,i){
                        if(el.nodeId == recv[0].nodeId){
                            _CvibNodeArr[i] = new CvibInfo(signalArr[ii].nodeId, signalArr[ii].name, signalArr[ii].Lat, signalArr[ii].Lng, signalArr[ii].addr1,
                                signalArr[ii].addr2, signalArr[ii].addr3, date, 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);
                        }
                    });
                }else{
                    _CvibNodeArr.push(new CvibInfo(signalArr[ii].nodeId, signalArr[ii].name, signalArr[ii].Lat, signalArr[ii].Lng, signalArr[ii].addr1,
                        signalArr[ii].addr2, signalArr[ii].addr3, date, 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(_Level == 0 || _Level == 1){
            _CvibNodeArr.forEach(function (el) {
                for (var ii = 0; ii < signalArr.length; ii++) {
                    if(el.nodeId == signalArr[ii].nodeId){
                        el.emptyCvibCircleImg();
                        el.emptyCvibInfoImg();
                    }
                }
            });
            _CvibNodeArr.forEach(function (el) {
                for (var ii = 0; ii < signalArr.length; ii++) {
                    if(el.nodeId == signalArr[ii].nodeId){
                        //console.log(el.nodeId + " 셋팅");
                        el.setCircle();
                        el.setCvibInfo();
                    }
                }

            });
        }

        $('#iframeBottomList').contents().find('#' + nodeId).find('#oprTrans').empty().text(oprTrans);
        $('#iframeBottomList').contents().find('#' + nodeId).find('#oprInd').empty().text(oprInd);
        $('#iframeBottomList').contents().find('#' + nodeId).find('#oprTurnoff').empty().text(oprTurnoff);
        $('#iframeBottomList').contents().find('#' + nodeId).find('#oprBlink').empty().text(oprBlink);
        $('#iframeBottomList').contents().find('#' + nodeId).find('#oprManual').empty().text(oprManual);
        $('#iframeBottomList').contents().find('#' + nodeId).find('#errScu').empty().text(errScu);
        $('#iframeBottomList').contents().find('#' + nodeId).find('#errCenter').empty().text(errCenter);
        $('#iframeBottomList').contents().find('#' + nodeId).find('#errCont').empty().text(errCont);
        $('#iframeBottomList').contents().find('#' + nodeId).find('#counter').empty().text(counter);
        $('#iframeBottomList').contents().find('#' + nodeId).find('#date').empty().text(date);


            for (var ii = 0; ii < _signalInfoArr.length; ii++) {
            //console.log(_signalInfoArr[ii].nodeId + " || " + nodeId);
            if (_signalInfoArr[ii].nodeId == nodeId) {
                _signalInfoArr[ii].date = date;
                _signalInfoArr[ii].commDate = new Date();
                //console.log(date);
/*
                if (_signalInfoArr[ii].date != null) {
                    var signaldate = moment(date).format('YYYY-MM-DD HH:mm:ss'); // 통신데이터시간
                    var now = new Date();
                    var preDate = moment(now.getTime()).add("-3", "s").format("YYYY-MM-DD HH:mm:ss");


                    if (signaldate > preDate) { //시간이 null거나 3초전이거나
                        _signalInfoArr[ii].status = 1;
                    } else {
                        _signalInfoArr[ii].status = 2;
                    }
                    //console.log(_signalInfoArr[ii].nodeId +" "+_signalInfoArr[ii].date+ "|||||||||" + signaldate + " ||||"+ preDate + " " + _signalInfoArr[ii].status)
                }*/
                break;
            }
        }

    }
}

function wsClose(message) {
    console.log("Disconnect ... ");
    //wsSendMessage('ws')
}

function wsError(message) {
    //console.log("Error ... ");
    console.log(message);
}

/*
	직진 좌회전 보행 유턴
	     9_9_9_9
	light로 값 변환시켜준다
	* 좌회전때 비보호가 1일때
 */
function setCvibSttsFnc(unprotected, light, dirCode, stts, cvibStts) {
    if (cvibStts === undefined || cvibStts != "") {
        //TODO: 20230221
        cvibStts = '9_9_9_9';
    }
    if (light == '1') {
        var temp = cvibStts.substring(1);
        cvibStts = stts + temp;
    } else if (light == '2') {
        var tempS = cvibStts.substring(0, 2);
        var tempE = cvibStts.substring(3);
        //stts =(unprotected == 0) ? stts : 1;
        cvibStts = tempS + stts + tempE;
    } else if (light == '3') {
        var tempS = cvibStts.substring(0, 4);
        var tempE = cvibStts.substring(5);
        cvibStts = tempS + stts + tempE;
    } else if (light == '7') {
        var 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 " ";


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

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

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

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

    var 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) {
    var 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);
};