/*
 * 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 openMachineEditor(machineid) {
    app.dialog.preloader("Loading...");

    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: {}
                    };
                    var tabindex = 0;
                    for (var k in resp.info) {
                        if (resp.info.hasOwnProperty(k)) {
                            context.info[k] = {
                                name: k,
                                value: (resp.formdata.inputtypes[k] == "select" ? "val_" : "") + 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") {
                                console.log(resp.formdata.options[k]);
                                var options = [];
                                for (var m in resp.formdata.options[k]) {
                                    if (resp.formdata.options[k].hasOwnProperty(m)) {
                                        options.push({
                                            value: "val_" + m,
                                            label: resp.formdata.options[k][m]
                                        });
                                    }
                                }
                                console.log(options);
                                context.info[k].options = options;
                            }
                            tabindex++;
                        }
                    }
                    router.navigate("/machineeditor", {
                        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 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,
                        type: resp.type,
                        icon: resp.icon,
                        machineprops: {
                            machineid: {
                                name: "machineid",
                                value: resp.id,
                                label: "ID",
                                icon: "fas fa-hashtag"
                            }
                        },
                        editable: resp.editable
                    };

                    if (resp.clientinfo != [] && Object.entries(resp.clientinfo).length > 0) {
                        context.clientinfo = {
                            name: resp.clientinfo.name
                        };
                        if (resp.clientinfo.phone) {
                            context.clientinfo.phone = resp.clientinfo.phone;
                            context.clientinfo.phonestripped = resp.clientinfo.phone.replace(/\D/g, '');
                        }
                        if (resp.clientinfo.billingaddress) {
                            context.clientinfo.billingaddress = resp.clientinfo.billingaddress.replace("\n", "\n<br />");
                        }
                        if (resp.clientinfo.mailingaddress) {
                            context.clientinfo.mailingaddress = resp.clientinfo.mailingaddress.replace("\n", "\n<br />");
                        }
                    }
                    var tabindex = 0;
                    for (var k in resp.info) {
                        if (resp.info.hasOwnProperty(k)) {
                            switch (k) {
                                case "type":
                                case "clientid":
                                    // skip these
                                    break;
                                default:
                                    var value = resp.info[k];
                                    if (value == false || value == 0) {
                                        value = false;
                                    } else {
                                        value = value.toString().replace("\n", " <br />");
                                    }
                                    context.machineprops[k] = {
                                        name: k,
                                        value: value,
                                        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
                                    };
                                    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 saveMachineEdits(machineid) {
    app.dialog.preloader("Saving...");

    var machinedata = {
        id: machineid
    };
    $("#machineform .machinefield").each(function (i, o) {
        if ($(this).parent().is(".smart-select")) {
            machinedata[$(this).attr("name")] = app.smartSelect.get('#smartselect-' + $(this).attr("name")).getValue().replace("val_", "");
        } else {
            machinedata[$(this).attr("name")] = $(this).val();
        }
    });

    apirequest(
            "editmachine",
            machinedata,
            function (resp) {
                app.dialog.close();
                if (resp.status == "ERROR") {
                    app.dialog.alert(resp.msg, "Error");
                } else {
                    app.toast.create({
                        text: 'Machine saved!',
                        closeTimeout: 2000,
                    }).open();
                    openMachineInfo(machineid);
                }
            },
            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")
            );
}

$("#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();
    }
});