
/*
 서버시간 요청 함수
 */
var _time_id = null;
/*requestService("getServerDate","",getServerTimeCallback,true);
function getServerTimeCallback(result, statusText, xhr){
    _sever_time =result.serverDate;

}*/

if(_time_id == null) {
    _time_id = setInterval(severTimeInterval,1000);
}

function severTimeInterval(){
    $("#serverTime").text(moment(_sever_time).add("1", "s").format("YYYY-MM-DD HH:mm:ss"));
    _sever_time = moment(_sever_time).add("1", "s").format("YYYY-MM-DD HH:mm:ss");
}

/*
 *  LOG 함수
 */
var _fileListTbody = "";
var _fileViewTimeout = null;
function fileView(name, path) {
    if (_fileViewTimeout != null) {
        clearInterval(_fileViewTimeout);
        _fileViewTimeout = null;
    }

    $("#fileTbody").empty();
    var endPoint = 0;

    function requestLog(){
        $.ajax({
            url:"/getFileView",
            type:"POST",
            data:"fileName="+name+"&filePath="+path+"&preEndPoint="+endPoint,
            success:function (data) {

                $("#logFileName").text(name);

                test=data;
                endPoint = data.endPoint;
                if(data.log.length < 1) return;

                var tbody="<tr><td>"+data.log+"</td></tr>";

                $("#FilesForm").css("display","none");
                $("#FileForm").css("display","block");

                //$("#fileTbody").empty();
                tbodyAppend("fileTbody",tbody);
                $("#logScroll").scrollTop($('#logScroll')[0].scrollHeight);
            },
            error:function (request,status,e) {
                console.log("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+e);
            }
        }).done

        if(_fileViewTimeout == null ){
            _fileViewTimeout = setInterval(requestLog, 1000);
        }
    }
    requestLog();
}

function fileDownload(name,path) {
    location.href="/getFileDownload?fileName="+name+"&filePath="+path;
}

function fileDelete(name,path) {
    if (!confirm(name+"을 삭제합니다.")) {
        return;
    }

    $.ajax({
        url:"/getFileDelete",
        type:"POST",
        data:"fileName="+name+"&filePath="+path,
        success:function (data) {
            alert("삭제 했습니다.");
            $("#logTbody").empty();
            fileList = data;
            _fileListTbody="";

            initLogFileList(data);
            tbodyAppend("logTbody", _fileListTbody);
            $('.tree-basic').treegrid();

        },
        error:function (request,status,e) {
            alert("삭제를 실패했습니다.");
            console.log("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+e);
        }
    }).done
}

function initLogFileList(fileList) {

    fileList.forEach(function (el, index) {
        console.log(el.type + ', ' + el.fileName + ', ' + el.filePath);

        if (el.type == "dir") {
            if (el.fileName === "logs"){
                //_fileListTbody += "<tr class='treegrid-"+el.id+" expanded'>";
            }
            else {
                if (el.parentId  > 1) {
                    _fileListTbody += "<tr class='treegrid-"+el.id+" expanded treegrid-parent-"+el.parentId+"'>";
                }
                else {
                    _fileListTbody += "<tr class='treegrid-"+el.id+"'>";
                }
                _fileListTbody += "<td>"+el.fileName+"</td>";
                _fileListTbody += "</tr>";
            }
        }
        else {
            if (el.parentId  > 1) {
                _fileListTbody += "<tr class='treegrid-"+el.id+" expanded treegrid-parent-"+el.parentId+"'>";
            }
            else {
                _fileListTbody += "<tr class='treegrid-"+el.id+" treegrid-parent-"+el.parentId+"'>";
            }
            _fileListTbody +="<td>"+el.fileName+" ("+el.fileSize+" Byte)&nbsp;&nbsp;&nbsp;&nbsp;</td>";
            _fileListTbody += "<td><a href=javascript:fileView('" + el.fileName+"','" + el.filePath + "');>보기</a>&nbsp;&nbsp;</td>";
            _fileListTbody += "<td><a href=javascript:fileDownload('" + el.fileName+"','" + el.filePath +"');>다운로드</a>&nbsp;&nbsp;</td>";
            //_fileListTbody += "<td><a href=javascript:fileDelete('" + el.fileName + "','" + el.filePath + "''\);>delete</a>&nbsp;&nbsp;</td>";

            _fileListTbody += "</tr>";
        }

        if (el.fileInfos.length > 0) initLogFileList(el.fileInfos);
    });
    return _fileListTbody;
}

/*
 * CONTROLLER 명령 함수
 */

// 제어기 연결해제
function disconnectController(id) {
    if (!confirm("연결을 종료 하시겠습니까?")) {
        return;
    }

    $.ajax({
        url:"/disconnectController",
        type:"POST",
        data:"id="+id,
        success:function (data) {
            alert(data);
            location.href = "/controller";
        },
        error:function (request,status,e) {
            console.log("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+e);
        }
    }).done
}

// 전체 제어기 접속횟수 초기화
function allDisconnectController() {
    if (!confirm("전체 제어기의 연결을 종료 하시겠습니까?")) {
        return;
    }

    $.ajax({
        url:"/allDisconnectController",
        type:"POST",
        success:function (data) {
            alert(data);
            location.href = "/controller";
        },
        error:function (request,status,e) {
            console.log("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+e);
        }
    }).done
}

// 제어기 접속횟수 초기화
function resetConnCount(id) {
    if (!confirm("접속횟수를 초기화 하시겠습니까?")) {
        return;
    }

    $.ajax({
        url:"/resetConnCount",
        type:"POST",
        data:"id="+id,
        success:function (data) {
            alert(data);
            location.href = "/controller";
        },
        error:function (request,status,e) {
            console.log("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+e);
        }
    }).done
}

// 전체 제어기 접속횟수 초기화
function allResetConnCount() {
    if (!confirm("전체 제어기의 접속횟수를 초기화 하시겠습니까?")) {
        return;
    }

    $.ajax({
        url:"/allResetConnCount",
        type:"POST",
        success:function (data) {
            alert(data);
            location.href = "/controller";
        },
        error:function (request,status,e) {
            console.log("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+e);
        }
    }).done}


// 제어기 리셋
function resetController(id) {
}

// 전체 제어기 리셋
function allResetController(id) {
}

function controllerPing(id, name, ip) {
    var infoData = "ping: " + id + ", " + name + ", " + ip + "  =====>     <br/>";
    tbodyAppend("fileTbody", infoData);

    $.ajax({
        url:"/getPing",
        type:"POST",
        data:"ipAddr="+ip,
        success:function (data) {
            var result = "<===== " + data + "<br/>";
            tbodyAppend("fileTbody", result);
        },
        error:function (request,status,e) {
            console.log("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+e);
        }
    }).done
}

var _controllerList = "";
function AllControllerPing() {
    if (_controllerList == "") {
        return;
    }
    $("#fileTbody").innerText = "";

    //document.getElementById("fileTbody").innerHTML = data;
    for (var el in _controllerList) {
        controllerPing(_controllerList[el].ctlr_ID, _controllerList[el].istl_LCTN_NM, _controllerList[el].ctlr_IP);
    }
}

/*
 * Tbody 데이터 넣기
 */
function tbodyAppend(tagId, tbodyData) {
    $("#"+tagId).append(tbodyData);
}
