//DISCOVERY LIST
var arrayAmplifier;
var discoveryList = new Array();

var ws = null;

var ws_ip = "127.0.0.1";
var ws_port = "5678";

var loginLocal = 0;
var httpSecure = 1;

var usernameHttp = "admin";
var passwordHttp = "admin";

var cmd_get_neighbour_list = "get_neighbour_list";
var cmd_oem_get_status = "oem_get_status";
var cmd_oem_remove_code = "oem_remove_code";
var cmd_oem_set_code = "oem_set_code";
var cmd_oem_check_code = "oem_check_code";

var oem_status = 0
var oem_check_type = 0


jQuery(function() {

    $("body").on("click", "#setOEMConfigButton", function() {
        $("#oemOldCode").removeClass("is-invalid");
        $("#oemOldCode").removeClass("is-valid");
        $("#oemOldCode").val("");
        $("#oemNewLabel").val("");
        $("#oemNewCode").val("");
        if (oem_status == 1) {
            $("#requestPreviousOEM").css('display', 'none');
        }
        if (oem_status == 2) {
            $("#requestPreviousOEM").css('display', '');
        }
        $("#setOEMParametersModal").modal("show");
    });

    $("body").on("click", "#deleteOEMConfigButton", function() {
        $("#oemOldCodeRemove").removeClass("is-invalid");
        $("#oemOldCodeRemove").removeClass("is-valid");
        $("#oemOldCodeRemove").val("");
        if (oem_status == 1) {
            $("#requestPreviousOEMRemove").css('display', 'none');
        }
        if (oem_status == 2) {
            $("#requestPreviousOEMRemove").css('display', '');
        }
        $("#removeOEMParametersModal").modal("show");
    });

    $("body").on("click", "#setOEMButton", function() {
        $("#oemOldCode").removeClass("is-invalid");
        $("#oemOldCode").removeClass("is-valid");
        $("#statusOEMText").val("Warning, this operation can't be cancelled later !")
        var oemContent = new Object()
        oemContent.label = "";
        oemContent.model = "";
        oemContent.desc = "";
        oemContent.danteCap = false;

        oemContent.label = $("#oemNewLabel").val();
        oemContent.model = $("#oemNewModel").val();
        oemContent.desc = $("#oemNewDesc").val();
        if ($("#oemNewDanteCap").is(':checked')) {
            oemContent.danteCap = true;
        }
        newLabel = $("#oemNewLabel").val();
        newCode = $("#oemNewCode").val();

        var oemContentTxt = JSON.stringify(oemContent)
        let resultTxt = oemContentTxt.replaceAll("\"", "\\\"");

        if (newLabel.length < 5) {
            $("#oemNewLabel").addClass("is-invalid");
        } else {
            $("#oemNewLabel").removeClass("is-invalid");
            if (newCode.length != 10) {
                $("#oemNewCode").addClass("is-invalid");
            } else {
                $("#oemNewCode").removeClass("is-invalid");
                if (oem_status == 1) {
                    ws.send(commandToJSON($.fn.getCommandFromArgs(cmd_oem_set_code, 0, "null", resultTxt, newCode)));
                    // ws.send(commandToJSON($.fn.getCommandFromArgs(cmd_oem_set_code, 0, "null", newLabel, newCode)));
                    setTimeout(function() {
                        $.fn.updateOEMStatus();
                        $("#setOEMParametersModal").modal("hide");
                    }, 2000);
                } else if (oem_status == 2) {
                    oem_check_type = 1;
                    ws.send(commandToJSON($.fn.getCommandFromArgs(cmd_oem_check_code, 0, "null", "null", $("#oemOldCode").val())));
                }
            }
        }
    });

    $("body").on("click", "#removeOEMButton", function() {
        $("#oemOldCodeRemove").removeClass("is-invalid");
        $("#oemOldCodeRemove").removeClass("is-valid");
        $("#statusOEMTextRemove").val("Warning, this operation can't be cancelled later !")
        newLabel = $("#oemNewLabel").val();
        newCode = $("#oemNewCode").val();

        if (oem_status == 1) {
            setTimeout(function() {
                $.fn.updateOEMStatus();
                $("#statusOEMTextRemove").val("Nothing to remove !")
                $("#removeOEMParametersModal").modal("hide");
            }, 2000);
        } else if (oem_status == 2) {
            oem_check_type = 2;
            ws.send(commandToJSON($.fn.getCommandFromArgs(cmd_oem_check_code, 0, "null", "null", $("#oemOldCodeRemove").val())));
        }
        // ws.send(commandToJSON($.fn.getCommandFromArgs(cmd_oem_remove_code, 0, "null", "null", "null")));

        // setTimeout(function() {
        //     $.fn.updateOEMStatus();
        //     $("#removeOEMParametersModal").modal("hide");
        // }, 2000);
    });

    $("body").on("change", "input[type=radio][name=oemNewDanteCap]", function(e) {
        $("#oemNewDanteCap").attr("checked", true);
    });


    $.fn.createWebSocket();
});

//LOAD FILE FROM SERVER
function loadFile(filePath) {
    var result = null;
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", filePath, false);
    xmlhttp.send();
    if (xmlhttp.status == 200) {
        result = xmlhttp.responseText;
        lines = result.split("\n");
        usernameHttp = lines[0];
        passwordHttp = lines[1];
    }
}

//GENERATE RANDOM VALUE
$.fn.getRandomValue = function() {
    let ret = 0;
    let rnd = 0;
    rnd = Math.random();
    ret = Math.floor((Date.now() * (rnd * 463)) + (rnd * 569));
    return ret;
}

//GET COMMAND OBJECT FROM ARGUMENTS
$.fn.getCommandFromArgs = function(cmd, arg1, arg2, arg3, arg4) {
    var temp_request = new commandConstructor();

    //SET COMMAND OBJECT PARAMETERS
    temp_request.command = cmd;
    temp_request.query_arg1 = arg1;
    temp_request.query_arg2 = arg2;
    temp_request.query_arg3 = arg3;
    temp_request.query_arg4 = arg4;
    temp_request.query_id = $.fn.getRandomValue();
    temp_request.query_time = 1;

    return temp_request;
}

// CONVERT COMMAND JAVASCRIPT TO JSON READABLE
function commandToJSON(cmd) {
    var ret = "";
    ret += "[";
    ret += "{";
    ret += "\"command\":\"" + cmd.command + "\",";
    if (cmd.query_arg1 != "null")
        ret += "\"arg1\": 0,";
    if (cmd.query_arg2 != "null") {
        if (typeof(cmd.query_arg2) === 'string')
            ret += "\"arg2\": \"" + cmd.query_arg2 + "\",";
        else
            ret += "\"arg2\": " + cmd.query_arg2 + ",";
    }
    if (cmd.query_arg3 != "null")
        if (typeof(cmd.query_arg4) === 'string')
            ret += "\"arg3\": \"" + cmd.query_arg3 + "\",";
        else
            ret += "\"arg3\": " + cmd.query_arg3 + ",";
    if (cmd.query_arg4 != "null") {
        if (typeof(cmd.query_arg4) === 'string')
            ret += "\"arg4\": \"" + cmd.query_arg4 + "\",";
        else
            ret += "\"arg4\": " + cmd.query_arg4 + ",";
    }
    ret += "\"query_time\":" + cmd.query_id;
    ret += "}";
    ret += "]";
    return ret;
}

//WEB SOCKET CREATION
$.fn.createWebSocket = function() {
    var href = $(location).attr("href");
    var r = /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/;
    var t;
    if (href.match(r) != null) {
        //IP ADDRESS
        t = href.match(r);
        loginLocal = 1;
    } else {
        t = new Array(1);
        var x = 0;
        if (href.indexOf(".me/") >= 0) {
            x = href.indexOf(".me/");
            x = x + 3;
        } else
            x = href.length;
        t[0] = href.slice(7, x);
        httpSecure = 1;
    }
    //TEST IF SERVER IS AVAILABLE
    if (t) {
        // displayVal("location server", t[0]);
        if (t[0]) {
            ws_ip = t[0];
        }
        var ws_string = "ws://" + ws_ip + ":" + ws_port + "/";
        if (httpSecure === 1) {
            loadFile("id.txt");
            ws_string = "ws://" + usernameHttp + ":" + passwordHttp + "@" + ws_ip + ":" + ws_port + "/";
        }

        if (ws === null || ws.readyState === WebSocket.CLOSED) {
            ws = new WebSocket(ws_string);

            ws.onmessage = function wsOnMessage(event) {
                $.fn.receiveCommandWS(event);
                return false;
            };

            ws.onopen = function wsOnOpen(event) {
                $.fn.updateOEMStatus();
            };

            ws.onerror = function(event) {
                setTimeout(function() {
                    runSubscription = false;
                    $("#mainLoader").addClass("is-active");
                    $.fn.createWebSocket();
                }, 2000);
            };

            ws.onclose = function(e) {
                setTimeout(function() {
                    $("#mainLoader").addClass("is-active");
                    $.fn.createWebSocket();
                }, 2000);
            };
        }
    }
}

$.fn.receiveCommandWS = function(event) {
    var msg = null;
    var i = -1;
    try {
        if (event.data != "JSON is not valid.") {
            msg = JSON.parse(event.data);
            if (msg) {
                i = -1
                var msgR = JSON.parse(event.data)
                switch (msgR.command) {
                    case cmd_get_neighbour_list:
                        try {
                            var files = JSON.parse(msgR.arg2);
                            if (discoveryList.length < 1) {
                                discoveryList = new Array(files.length);
                                for (var c = 0; c < files.length; c++) {
                                    discoveryList[c] = new discoveredAmpConstructor(files[c]);
                                }
                            } else if (discoveryList.length != files.length) {
                                for (var d = 0; d < (files.length - discoveryList.length); d++) {
                                    discoveryList.push(new discoveredAmpConstructor(files[discoveryList.length + d]));
                                }
                            } else if (discoveryList.length === files.length) {
                                for (var e = 0; e < discoveryList.length; e++) {
                                    if (discoveryList[e].desc != files[e].desc && e > 0) {
                                        discoveryList[e].desc = files[e].desc;
                                        let idDest1 = "#assignGroupTabAmpName" + e;
                                        let idDest2 = "#groupAssignAmpSelectedName";
                                        if ($(idDest1))
                                            $(idDest1).html(discoveryList[e].desc);
                                        if (groupAssignAmplifierSelected === e) {
                                            $(idDest2).html(discoveryList[e].desc);
                                        }
                                    }
                                    discoveryList[e].hw_addr = files[e].hw_addr;
                                    if (discoveryList[e].ip_addr != files[e].ip_addr) {
                                        let idDest3 = "#dldcds" + e;
                                        discoveryList[e].ip_addr = files[e].ip_addr;
                                        if ($(idDest3))
                                            $(idDest3).html(discoveryList[e].ip_addr);
                                    }
                                    discoveryList[e].alive = files[e].alive;
                                    discoveryList[e].last_report_time = files[e].last_report_time;
                                    discoveryList[e].model = files[e].model;
                                    discoveryList[e].cloud_device_name = files[e].cloud_device_name;
                                }
                            }
                        } catch (e) {
                            // console.log("Fail to parse get_neighbour_list");
                        }

                        if (discoveryList.length > 0) {
                            $.fn.updateAmpInfo();
                        }
                        break;
                    case cmd_oem_get_status:
                        try {
                            var status = msgR.arg2;
                            if (status.oem_code_enable) {
                                oem_status = 2;
                                $("#oemStatus").val("Enable");
                                $("#oemLabel").val(status.oem_label);
                            } else {
                                oem_status = 1;
                                $("#oemStatus").val("Disable");
                                $("#oemLabel").val("Disable");
                            }
                        } catch (e) {
                            console.log("Fail to parse oem_get_status");
                        }
                        break;
                    case cmd_oem_check_code:
                        if (msgR.arg1 === "OK") {
                            if (oem_check_type == 1) {
                                $("#oemOldCode").addClass("is-valid");
                                newLabel = $("#oemNewLabel").val();
                                newCode = $("#oemNewCode").val();
                                ws.send(commandToJSON($.fn.getCommandFromArgs(cmd_oem_set_code, 0, "null", newLabel, newCode)));
                                setTimeout(function() {
                                    $.fn.updateOEMStatus();
                                    $("#setOEMParametersModal").modal("hide");
                                }, 2000);
                            } else if (oem_check_type == 2) {
                                $("#oemOldCodeRemove").addClass("is-valid");
                                ws.send(commandToJSON($.fn.getCommandFromArgs(cmd_oem_remove_code, 0, "null", "null", "null")));
                                setTimeout(function() {
                                    $.fn.updateOEMStatus();
                                    $("#removeOEMParametersModal").modal("hide");
                                }, 2000);
                            }

                        } else {
                            if (oem_check_type == 1) {
                                $("#oemOldCode").addClass("is-invalid");
                                $("#statusOEMText").val("Old OEM code is invalid. Please try again !")
                            } else if (oem_check_type == 2) {
                                $("#oemOldCodeRemove").addClass("is-invalid");
                                $("#statusOEMTextRemove").val("Old OEM code is invalid. Please try again !")
                            }
                        }
                        oem_check_type = 0;
                        break;
                    default:
                        break;
                }
                // }
            }
        } else
            console.log("JSON NOT VALID");
    } catch (e) {
        // if (i > -1)
        //     console.log("error in JSON parse : " + e + " // msg : " + msg + " // request : " + request_pool[i].toString());
        // else
        console.log("error in JSON parse : " + e + " // msg : " + msg);
    }
}

$.fn.updateAmpInfo = function() {
    $("#ipAddressStatus").val(discoveryList[0].ip_addr);
    $("#macAddressStatus").val(discoveryList[0].hw_addr);
    $("#modelStatus").val(discoveryList[0].model);
    $("#serialNumberStatus").val(discoveryList[0].serial);
}

$.fn.updateOEMStatus = function() {
    ws.send(commandToJSON($.fn.getCommandFromArgs(cmd_get_neighbour_list, 0, "null", "null", "null")));
    ws.send(commandToJSON($.fn.getCommandFromArgs(cmd_oem_get_status, 0, "null", "null", "null")));
}

//CONSTRUCTOR OF DISCOVERED AMPLIFIER
function discoveredAmpConstructor(arg) {
    this.hw_addr = arg.hw_addr;
    this.ip_addr = arg.ip_addr;
    this.desc = arg.desc;
    this.alive = arg.alive;
    this.last_report_time = arg.last_report_time;
    this.model = arg.model;
    this.cloud_device_name = arg.cloud_device_name;
    this.serial = arg.serial;
}

//CONSTRUCTOR OF COMMAND
function commandConstructor() {
    this.command = null;
    this.query_arg1 = null;
    this.query_arg2 = null;
    this.query_arg3 = null;
    this.query_arg4 = null;

    this.response_arg1 = null;
    this.response_arg2 = null;

    this.status = 0;
    this.query_time = Date.now();
    this.query_id = 0;
}