/*
 * Copyright 2020 Netsyms Technologies.
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

function getMachineSearchHistory() {
    var history = getStorage("machinehistory");
    if (history != null) {
        return JSON.parse(history);
    } else {
        return [];
    }
}

function addMachineToSearchHistory(machineid) {
    var history = getMachineSearchHistory();

    for (var i = 0; i < history.length; i++) {
        if (history[i] == machineid) {
            history.splice(i, 1);
        }
    }
    // Add the code back to the list so it's at the top
    history.push(machineid);

    while (history.length > 10) {
        history.shift();
    }
    setStorage("machinehistory", JSON.stringify(history));
}

function openMachineInfo(machineid) {
    app.dialog.preloader("Searching...");

    apirequest(
            "lookup",
            {
                id: machineid
            },
            function (resp) {
                app.dialog.close();
                if (resp.status == "ERROR") {
                    app.dialog.alert(resp.msg, "Error");
                } else {
                    var context = {
                        machineid: resp.id,
                        info: {}
                    };
                    if (resp.editable) {
                        context.editable = true;
                    }
                    var tabindex = 0;
                    for (var k in resp.info) {
                        if (resp.info.hasOwnProperty(k)) {
                            context.info[k] = {
                                name: k,
                                value: resp.info[k],
                                type: (typeof resp.formdata.inputtypes[k] == "string" ? resp.formdata.inputtypes[k] : "text"),
                                label: (typeof resp.formdata.labels[k] == "string" ? resp.formdata.labels[k] : k),
                                icon: (typeof resp.formdata.icons[k] == "string" ? resp.formdata.icons[k] : "fas fa-square"),
                                tabindex: tabindex
                            };
                            if (context.info[k].type == "select") {
                                context.info[k].options = resp.formdata.options[k];
                            }
                            tabindex++;
                        }
                    }
                    addMachineToSearchHistory(resp.id);
                    router.navigate("/machine", {
                        context: context
                    });
                }
            },
            function (xhr) {
                app.dialog.close();
                var error = $.parseJSON(xhr.responseText);
                if (error && typeof error.msg != 'undefined') {
                    app.dialog.alert(error.msg, "Error");
                } else {
                    app.dialog.alert("A server or network error occurred.", "Error");
                }
            },
            getStorage("username"),
            getStorage("password")
            );
}

function enableEditMachine() {
    $(".machinefield").prop("disabled", false);
    $(".machinefield-clear-button").removeClass("display-none");
    $("#save-fab").removeClass("display-none");
    $("#canceledit-fab").removeClass("display-none");
    $("#menu-fab").addClass("display-none");
}

function disableEditMachine() {
    $(".machinefield").prop("disabled", true);
    $(".machinefield-clear-button").addClass("display-none");
    $("#save-fab").addClass("display-none");
    $("#canceledit-fab").addClass("display-none");
    $("#menu-fab").removeClass("display-none");
}

function saveMachineEdits() {
    // TODO
}

$("#app").on("click", "#machineEditButton", enableEditMachine);

$("#app").on("keypress", "#machineform .machinefield", function (evt) {
    // Catch Enter key in form because it's likely a barcode scanner
    // Instead switch to the next input box
    if (evt.which == '13') {
        console.log("enter detected");
        evt.preventDefault();

        var tabindex = parseInt($(this).attr("tabindex"));
        $("#machineform .machinefield[tabindex=" + (tabindex + 1) + "]").focus();
    }
});

$("#app").on("smartselect:beforeopen", "#machineform", function (evt) {
    // Don't allow changing selection if rest of form is readonly
    if ($(".machinefield").prop("disabled")) {
        evt.detail.prevent();
    }
});