/*
 * 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('<li><a class="item-link item-content hapticbtn" href="/track/' + history[i] + '">'
                + '<div class="item-inner"><div class="item-title">'
                + history[i]
                + '</div></div></a></li>');
    }
}

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( {to, resolve, reject}) {
    app.dialog.preloader("Loading...");

    apirequest(
            SETTINGS.apis.track,
            {
                code: to.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" && MapControl.supported()),
                            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) {
                        if (resp.info.carrier_logo) {
                            context.info.push({label: "Carrier", value: "<img style=\"height: 2em; padding: 0.667em; max-width: 80%;\" src=\"" + resp.info.carrier_logo + "\" />"});
                        } else {
                            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)});
                    }
                    if (resp.info.carrier_tracking_url) {
                        context.carrierurl = resp.info.carrier_tracking_url;
                    }
                    if (resp.info.carrier_attribution) {
                        context.carrier_attribution = resp.info.carrier_attribution;
                    }

                    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({
                        content: compiledPages.trackresult(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));
}