/*
 * 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/.
 */

var scannerCodes = [];

function resetScanner() {
    scannerCodes = [];
    app.popup.close("#scanEventTypePopup");
    app.popup.close("#scanEventPopup");
    router.refreshPage();
}

function brokenScannerEsc() {
    app.dialog.confirm(
            "Clear list?",
            "Confirm",
            function () {
                resetScanner();
            },
            function () {
                // cancel
            }
    );
}

function brokenScannerScan() {
    scanBarcode(function (code) {
        playSound("scan");
        addCodeToScannerList(code);
    }, function (error) {
        app.dialog.alert(error, "Error");
    });
}

function brokenScannerAddTextEntry() {
    var code = $("#brokenscannerinput").val();
    if (code != "" && code.length > 5 && code.match(/^[0-9A-Z]+$/i)) {
        addCodeToScannerList(code);
        $("#brokenscannerinput").val("");
    } else {
        app.dialog.alert("That's not a valid tracking code.", "Error");
    }
}

function addCodeToScannerList(code) {
    code = code.toUpperCase();

    if (code != "" && code.length > 5 && code.match(/^[0-9A-Z]+$/i)) {
        // continue
    } else {
        app.dialog.alert("That's not a valid tracking code.", "Error");
        return;
    }

    var signatureregexes = [
        /^E[A-Z][0-9]{9}US$/, // Priority Mail Express
        /^[RV][A-Z][0-9]{9}[A-Z]{2}$/, // Registered mail
        /^(420[0-9]{5})?7[0-9]{19}$/ // Certified Mail
    ];

    /**
     * Regex of IMpb codes that don't need anything special
     * @type {RegExp}
     */
    var stcregex = /^(420[0-9]{5})?[0-9]{2}(001|023|055|056|112|113|134|135|138|140|141|142|164|209|211|259|265|269|346|361|389|390|419|431|490|502|551|563|612|624|671|701|702|703|704|723|746|748|790|791|793|794|905|906|907|909|971|972)[0-9]+$/;

    var signatureRequired = false;
    for (var i = 0; i < signatureregexes.length; i++) {
        if (code.match(signatureregexes[i])) {
            signatureRequired = true;
            break;
        }
    }

    if (!code.match(stcregex)) {
        signatureRequired = true;
    }

    var codeEntryTemplate = Template7.compile('<li class="codelist-entry" data-code="{{code}}">'
            + '  <div class="item-content">'
            + '    <div class="item-inner">'
            + '      <div class="item-title">{{code}}</div>'
            + '    </div>'
            + '  </div>'
            + '</li>');

    if (signatureRequired) {
        if (code.match(/^E[A-Z][0-9]{9}US$/)) {
            app.dialog.confirm(
                    "Does this item contain a waiver of signature endorsement?",
                    "Express Item",
                    function () {
                        $("#codelist").append(codeEntryTemplate({
                            code: code
                        }));
                    },
                    function () {
                        // cancel
                    }
            );
        } else {
            app.dialog.confirm(
                    "It looks like this item might require a signature or other special procedures. Add it anyways?",
                    "Special Item",
                    function () {
                        $("#codelist").append(codeEntryTemplate({
                            code: code
                        }));
                    },
                    function () {
                        // cancel
                    }
            );
        }
    } else {
        $("#codelist").append(codeEntryTemplate({
            code: code
        }));
    }
}

function chooseScanEvent() {
    if ($("#codelist li.codelist-entry").length <= 0) {
        app.dialog.alert("Nothing was entered!");
        return;
    }

    $("#codelist li.codelist-entry").each(function () {
        scannerCodes.push($(this).data("code"));
    });


    openEventPopup();
}

function openEventPopup() {
    var eventItemTemplate = Template7.compile('<li data-button="{{button}}" data-title="{{title}}" class="eventbutton" onclick=\'openEventTypePopup("{{title}}");\'>'
            + '  <div class="item-link item-content">'
            + '    <div class="item-media">{{button}}</div>'
            + '    <div class="item-inner">'
            + '      <div class="item-title">{{title}}</div>'
            + '    </div>'
            + '  </div>'
            + '</li>');

    $("#scanEventPopup ul.eventlist").html("");
    for (i in SETTINGS.scannerevents) {
        var event = SETTINGS.scannerevents[i];
        $("#scanEventPopup ul.eventlist").append(eventItemTemplate({
            button: event.button,
            title: event.title
        }));
    }

    app.popup.open("#scanEventPopup");
}

function openEventTypePopup(eventname) {
    var eventItemTemplate = Template7.compile('<li data-button="{{button}}" data-title="{{title}}" data-parenttitle="{{parenttitle}}" data-form3849="{{form3849}}" class="eventbutton eventtypebutton">'
            + '  <div class="item-link item-content">'
            + '    <div class="item-media">{{button}}</div>'
            + '    <div class="item-inner">'
            + '      <div class="item-title">{{title}}</div>'
            + '    </div>'
            + '  </div>'
            + '</li>');

    var eventafter = false;
    for (i in SETTINGS.scannerevents) {
        var event = SETTINGS.scannerevents[i];
        if (event.title == eventname) {
            eventafter = event.after;
            break;
        }
    }

    $("#scanEventTypePopup ul.eventlist").html("");
    for (i in eventafter) {
        var event = eventafter[i];
        $("#scanEventTypePopup ul.eventlist").append(eventItemTemplate({
            button: event.button,
            title: event.title,
            parenttitle: eventname,
            form3849: event.after == "3849" ? "1" : "0"
        }));
    }

    app.popup.open("#scanEventTypePopup");
}

function saveScanCode(code) {
    if (getStorage("scanevents") == null) {
        setStorage("scanevents", "[]");
    }
    var events = JSON.parse(getStorage("scanevents"));
    events.push(code);
    setStorage("scanevents", JSON.stringify(events));

    appendActivityLog("Scanned Item", code.event.join(' <i class="fas fa-chevron-right"></i> '), code.code + (code.form3849 == "" ? "" : "<br>Form 3849: " + code.form3849), "fas fa-barcode");
}

$(".view-main").off("click", "#codelist li.codelist-entry");

$(".view-main").on("click", "#codelist li.codelist-entry", function () {
    var entry = $(this);
    var code = entry.data("code");
    app.dialog.confirm(
            "Remove " + code + " from list?",
            "Confirm",
            function () {
                // delete
                entry.remove();
            },
            function () {
                // cancel
            }
    );
});

$("#app").off("click", "ul li.eventtypebutton");
$("#app").on("click", "ul li.eventtypebutton", function () {
    var eventname = $(this).data("parenttitle");
    var eventtypename = $(this).data("title");

    var scanEvent = [];
    scanEvent.push(eventname);
    scanEvent.push(eventtypename);

    if ($(this).data("form3849") == "1") {
        // TODO: make this not a hack
        app.dialog.prompt("Key in 3849 form", "3849 Form", function (formcode) {
            for (i in scannerCodes) {
                saveScanCode({
                    code: scannerCodes[i],
                    event: scanEvent,
                    form3849: formcode,
                    date: timestampToDateTimeString((new Date).getTime() / 1000)
                });
            }
            app.toast.show({
                text: 'Information recorded successfully!',
                position: "center",
                destroyOnClose: true,
                closeTimeout: 1000 * 3
            });
            resetScanner();
        }, function () {

        }, "");
    } else {
        for (i in scannerCodes) {
            saveScanCode({
                code: scannerCodes[i],
                event: scanEvent,
                form3849: "",
                date: timestampToDateTimeString((new Date).getTime() / 1000)
            });
        }
        app.toast.show({
            text: 'Information recorded successfully!',
            position: "center",
            destroyOnClose: true,
            closeTimeout: 1000 * 3
        });
        resetScanner();
    }
});

$("#brokenscannerinput").on('keypress', function (e) {
    if (event.key === "Enter") {
        brokenScannerAddTextEntry();
    }
});