//"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("/alarmHub").build();

//Disable send button until connection is established
//document.getElementById("sendButton").disabled = true;

connection.on("Remove", function (message) {
    var infoSpan = document.getElementById("common_header_left_text");
    if (infoSpan != null) {
        infoSpan.innerHTML = message;
    }
    console.log("Remove called");
});

connection.on("AddMessage", function (user, message, alarmInfoCount, warningInfoCount) {
    //var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    var msg = JSON.parse(message.toString());
    if (msg == null)
        return;
    var infoSpan = document.getElementById("common_header_left_text");
    if (infoSpan != null) {
        infoSpan.innerHTML = msg.Description;
    }
    UpdateAlarmBarVisibility(msg.Severity);
    if (msg.Severity === "Error" && msg.Acked === false) {
        var alarmAudio = document.getElementById("alarm_audio");
        if (alarmAudio == null) {
            alarmAudio = document.createElement("audio");
            alarmAudio.id = "alarm_audio";
            alarmAudio.src = "/WebConsole/audio/alarm.wav";
            alarmAudio.autoplay = "autoplay";
            alarmAudio.loop = "loop";
            //alarmAudio.muted = "false";
            //alarmAudio.controls = "controls";
            if (document.getElementById("common_header"))
                document.getElementById("common_header").appendChild(alarmAudio);
        }
    }
    var alarmCountSpan = document.getElementById("common_header_left_alarm_count");
    if (alarmCountSpan != null) alarmCountSpan.innerHTML = "报警次数:" + alarmInfoCount.toString();

    var warningCountSpan = document.getElementById("common_header_left_warning_count");
    if (warningCountSpan != null) warningCountSpan.innerHTML = "预警次数:" + warningInfoCount.toString();

    console.log("Add message called");
});

connection.on("Remove", function (user) {
    var infoSpan = document.getElementById("common_header_right_text");
    if (infoSpan != null) {
        infoSpan.innerHTML = "remove" + user;
    }
});

connection.on("MuteAlarmAduio", function () {
    var alarmAudio = document.getElementById("alarm_audio");
    if (alarmAudio != null) {
        //alarmAudio.muted = "muted";
        if (document.getElementById("common_header"))
            document.getElementById("common_header").removeChild(alarmAudio);
    }
});

connection.start().then(function () {
    console.log("start successfully");
    //var infoSpan = document.getElementById("common_header_left_text");
    //if (infoSpan != null) {
    //    infoSpan.innerHTML = "Main view SignalRStarted"+Math.random().toString();
    //}
}).catch(function (err) {
    return console.error(err.toString());
});

function Stop() {
    if (connection != null && connection.connectionState === "Connected") {
        connection.stop();
    }
}

function UpdateAlarmBarVisibility(severity) {
    var normalImgVisibility = severity === "Information" || severity == null ? "visible" : "hidden";
    var warningImgVisibility = severity === "Warning" ? "visible" : "hidden";
    var alarmImgVisibility = severity === "Error" ? "visible" : "hidden";

    var normalImg = document.getElementById("common_header_left_normal");
    var warningImg = document.getElementById("common_header_left_warning");
    var alarmImg = document.getElementById("common_header_left_alarm");

    if (normalImg != null) normalImg.style.visibility = normalImgVisibility;
    if (warningImg != null) warningImg.style.visibility = warningImgVisibility;
    if (alarmImg != null) alarmImg.style.visibility = alarmImgVisibility;
}

function AlarmBarClicked(id) {
    if (document.getElementById("alarm_information") != null) {
        return;
    }
    if (id === "common_header" &&
        document.getElementById("common_header_left_alarm") != null &&
        document.getElementById("common_header_left_alarm").style.visibility === "visible") {
        $.ajax({
            url: "/AlarmBar/AlarmAcked",
            contentType: 'application/json',
            //data: message,
            type: 'post',
            success: function (res) {
                console.log("Alarm information handled successfully, the response is:" + res);
                var alarmAudio = document.getElementById("alarm_audio");
                if (alarmAudio != null) {
                    //alarmAudio.muted = "muted";
                    if (document.getElementById("common_header"))
                        document.getElementById("common_header").removeChild(alarmAudio);
                }
            },
            error: function (msg) {
                console.log(msg);
            }
        });
    }
    var alarmInfoDiv = document.createElement("div");
    alarmInfoDiv.id = "alarm_information";
    alarmInfoDiv.style = "position: absolute;left:0%;top:0px;width:100%; height: 88.339%;background-image:url(/WebConsole/images/shared/alarmbarBackground.jpg);";


    var alarmInfoTable = document.createElement("table");
    alarmInfoTable.id = "alarm_information_table";
    alarmInfoTable.style = "width:100%;height:94%;border-collapse:collapse;";

    var alarmInfoTableHeader = document.createElement("thead");
    var headr = document.createElement("tr");
    headr.style = "display: table;width:100%;height:10%;table-layout:fixed;font-size: 22px;";
    var tableData = document.createElement("td");
    tableData.style = "width:20%;text-align: center;";
    tableData.innerText = "报警类型";

    var tableData1 = document.createElement("td");
    tableData1.style = "width:20%;text-align: center;";
    tableData1.innerText = "报警时间";

    var tableData3 = document.createElement("td");
    tableData3.style = "width:20%;text-align: center;";
    tableData3.innerText = "模块";

    var tableData2 = document.createElement("td");
    tableData2.style = "width:40%;text-align: center;";
    tableData2.innerText = "描述";
    headr.appendChild(tableData);
    headr.appendChild(tableData1);
    headr.appendChild(tableData3);
    headr.appendChild(tableData2);

    alarmInfoTableHeader.appendChild(headr);
    alarmInfoTable.appendChild(alarmInfoTableHeader);

    var tableBody = document.createElement("tbody");
    tableBody.style = "height:90%; overflow: hidden;display: block;overflow:hidden;overflow-y: auto;";

    $.ajax({
        url: "/AlarmBar/GetAlarmInformation",
        contentType: 'application/json',
        //data: message,
        type: 'get',
        success: function (res) {
            if (res == null) return;

            var msg = JSON.parse(res.toString());
            if (msg == null) return;
            msg.forEach(function (m) {
                var tempr = document.createElement("tr");
                tempr.style = "display: table;width:100%;height:10%;table-layout:fixed;font-size: 22px;";
                var tableData = document.createElement("td");
                tableData.style = "width:20%;text-align: center;";
                tableData.innerText = m.Severity === "Error" ? "报警" :
                    (m.Severity === "Warning" ? "预警" : "消息");
                var tableData1 = document.createElement("td");
                tableData1.style = "width:20%;text-align: center;";
                tableData1.innerText = new Date(m.OccurTime).getFullYear() + "-" + Pad(new Date(m.OccurTime).getMonth() + 1, 2) + "-" + Pad(new Date(m.OccurTime).getDate(), 2);
                var tableData3 = document.createElement("td");
                tableData3.style = "width:20%;text-align: center;";
                tableData3.innerText = m.Module;
                var tableData2 = document.createElement("td");
                tableData2.style = "width:40%;text-align: left;";
                tableData2.innerText = m.Description;
                tempr.appendChild(tableData);
                tempr.appendChild(tableData1);
                tempr.appendChild(tableData3);
                tempr.appendChild(tableData2);
                tableBody.appendChild(tempr);

            });
            console.log("Alarm information handled successfully, the response is:" + res);
        },
        error: function (msg) {
            console.log(msg);
        }
    });
    alarmInfoTable.appendChild(tableBody);
    alarmInfoDiv.appendChild(alarmInfoTable);

    var closeButtonImg = document.createElement("img");
    closeButtonImg.id = "close_alarm_information";
    //closeButtonImg.onclick = CloseAlarmInfoPage("close_alarm_information");
    closeButtonImg.onclick = function () { CloseAlarmInfoPage("close_alarm_information"); };
    closeButtonImg.style = "position: absolute; top:94.213%; left:45.156%;width:9.688%; height: 5.787%;";
    closeButtonImg.src = "/WebConsole/images/shared/closeButton.png";

    alarmInfoDiv.appendChild(closeButtonImg);
    //var bodyTab = document.getElementById("mainscrren_body");
    var bodyTab = document.getElementById("smartfuel_main_view");

    if (bodyTab != null) bodyTab.appendChild(alarmInfoDiv);

}

function CloseAlarmInfoPage(id) {
    if (document.getElementById("alarm_information") != null) {
        var mainbody = document.getElementById("smartfuel_main_view");
        if (mainbody != null) mainbody.removeChild(document.getElementById("alarm_information"));
    }
}

function Pad(num, n) {
    var len = num.toString().length;
    while (len < n) {
        num = "0" + num;
        len++;
    }
    return num;
}