/*
 * 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 openTrackingInfoPage(code) {
    if (typeof code == "undefined" || code == null || code == "") {
        app.input.validate("#trackingcode");
        return;
    }
    router.navigate("/track/" + code);
}
function addTrackingSuggestions() {
    $("#tracking-suggestion-list ul").html("");
    var history = getTrackingHistory();
    for (var i = history.length - 1; i >= 0; i--) {
        $("#tracking-suggestion-list ul").append('
'
                + '');
    }
}
function openTrackingBarcodeScanner() {
    scanBarcode(function (result) {
        var code = "";
        var coderegex = /^[0-9a-zA-Z]{5,40}$/;
        if (result.startsWith("https://helena.express/track#")) {
            code = result.split("#")[1];
        } else if (result.startsWith("http") && result.includes("#")) {
            if (coderegex.test(result.split("#")[1])) {
                code = result.split("#")[1];
            } else {
                app.dialog.alert("This app can't understand what's in that barcode.", "Error");
                return;
            }
        } else if (coderegex.test(result)) {
            code = result;
        } else {
            app.dialog.alert("This app can't understand what's in that barcode.", "Error");
            return;
        }
        code = code.toUpperCase();
        openTrackingInfoPage(code);
    }, function () {
        app.dialog.alert("Something went wrong and we can't scan right now.", "Error");
    });
}
function trackOpenAsync(routeTo, routeFrom, resolve, reject) {
    app.dialog.preloader("Loading...");
    apirequest(
            SETTINGS.apis.track,
            {
                code: routeTo.params.code,
                format: "json"
            },
            function (resp) {
                app.dialog.close();
                if (resp.status == "OK") {
                    addToTrackingHistory(resp.code);
                    var context = {
                        code: resp.code,
                        info: [
                            {label: "Tracking Code", value: resp.code},
                        ],
                        events: [],
                        map: {
                            enabled: (typeof resp.info.latitude == "number" && typeof resp.info.longitude == "number"),
                            latitude: resp.info.latitude,
                            longitude: resp.info.longitude,
                            accurate: resp.info.geoaccurate
                        }
                    };
                    if (resp.info.statustext) {
                        context.info.push({label: "Status", value: resp.info.statustext});
                    }
                    if (resp.info.carrier) {
                        context.info.push({label: "Carrier", value: resp.info.carrier});
                    }
                    if (resp.info.delivery_date) {
                        var deliverydatelabel = "Estimated delivery on";
                        if (resp.info.status == "DELIVERED") {
                            deliverydatelabel = "Delivered on";
                        }
                        context.info.push({label: deliverydatelabel, value: formatTimestamp("F j Y", resp.info.delivery_date_unixtime)});
                    }
                    for (var i = 0; i < resp.events.length; i++) {
                        context.events.push({
                            text: resp.events[i].text,
                            date: resp.events[i].timestring,
                            icon: "./assets/images/icons/" + resp.events[i].icon + ".svg"
                        });
                    }
                    if (context.events.length == 0) {
                        context.events = false;
                    }
                    resolve({
                        templateUrl: "pages/trackresult.html",
                    }, {
                        context: context
                    });
                } else {
                    app.dialog.alert(resp.msg, "Error");
                    reject();
                }
            },
            function (xhr) {
                app.dialog.close();
                try {
                    var error = $.parseJSON(xhr.responseText);
                    if (error && typeof error.msg != 'undefined') {
                        app.dialog.alert(error.msg, "Error");
                    } else {
                        app.dialog.alert("There's a server or network problem. Check your Internet connection or try again later.", "Error");
                    }
                } catch (ex) {
                    app.dialog.alert("There's a server or network problem. Check your Internet connection or try again later.", "Error");
                }
                reject();
            }, "GET");
}
function getTrackingHistory() {
    var history = getStorage("trackinghistory");
    if (history != null) {
        return JSON.parse(history);
    } else {
        return [];
    }
}
function addToTrackingHistory(code) {
    var history = getTrackingHistory();
    for (var i = 0; i < history.length; i++) {
        if (history[i] == code) {
            history.splice(i, 1);
        }
    }
    // Add the code back to the list so it's at the top
    history.push(code);
    while (history.length > 10) {
        history.shift();
    }
    setStorage("trackinghistory", JSON.stringify(history));
}