/*
 * 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 lasttrackingcode = "";

function locationArrayToString(location) {
    var locarray = [];
    if (location.street != "" && location.street != null) {
        locarray.push(location.street);
    }
    if (location.city != "" && location.city != null) {
        locarray.push(location.city);
    }
    if (location.state != "" && location.state != null) {
        locarray.push(location.state);
    }
    if (location.zip != "" && location.zip != null) {
        locarray.push(location.zip);
    }
    if (location.country != "" && location.country != "US" && location.country != null) {
        locarray.push(location.country);
    }
    return locarray.join(", ");
}

function trackingStatusToNiceString(status, icon) {
    if (typeof icon == 'undefined' || icon !== true) {
        var icon = false;
    }
    switch (status) {
        case "UNKNOWN":
            return (icon ? '<i class="fas fa-fw fa-question-circle"></i> ' : '') + "Unknown";
        case "PRE_TRANSIT":
            return (icon ? '<i class="fas fa-fw fa-ellipsis-h"></i> ' : '') + "Pre-transit";
        case "TRANSIT":
            return (icon ? '<i class="fas fa-fw fa-chevron-circle-right"></i> ' : '') + "In Transit";
        case "DELIVERED":
            return (icon ? '<i class="fas fa-fw fa-check-circle"></i> ' : '') + "Delivered";
        case "RETURNED":
            return (icon ? '<i class="fas fa-fw fa-undo-alt"></i> ' : '') + "Returned";
        case "FAILURE":
            return (icon ? '<i class="fas fa-fw fa-times-circle"></i> ' : '') + "Failure";
        default:
            return status;
    }
}

function openTrackingHistory(code) {
    var refresh = false;
    if (typeof code == "undefined") {
        trackingcode = lasttrackingcode;
        refresh = true;
    } else {
        trackingcode = code;
    }
    lasttrackingcode = trackingcode;
    var requestfinished = false;
    var trackingdialogopen = false;
    $.ajax({
        url: SETTINGS.trackingapi,
        dataType: 'json',
        data: {
            code: trackingcode
        },
        timeout: 15 * 1000,
        success: function (resp) {
            if (trackingdialogopen) {
                app.dialog.close();
                trackingdialogopen = false;
            }
            requestfinished = true;
            if (resp.status == "OK") {
                var infocontext = resp;

                infocontext.current.location.display = locationArrayToString(infocontext.current.location);
                infocontext.current.date = timestampToDateTimeString(infocontext.current.date);
                infocontext.current.status = trackingStatusToNiceString(infocontext.current.status, true);
                infocontext.addresses.from = locationArrayToString(infocontext.addresses.from);
                infocontext.addresses.to = locationArrayToString(infocontext.addresses.to);

                for (var i = 0; i < infocontext.history.length; i++) {
                    infocontext.history[i].location.display = locationArrayToString(infocontext.history[i].location);
                    infocontext.history[i].date = timestampToDateTimeString(infocontext.history[i].date);
                    infocontext.history[i].status = trackingStatusToNiceString(infocontext.history[i].status, true);
                }

                // Keep last five tracking codes in history
                var history = getStorage("trackingcodehistory");
                if (history == null) {
                    history = [];
                } else {
                    history = JSON.parse(history);
                }
                if (infocontext.code != "") {
                    // Search the history list and remove the current code if it's there
                    for (var i = 0; i < history.length; i++) {
                        if (history[i] == infocontext.code) {
                            history.splice(i, 1);
                        }
                    }
                    // Add the code back to the list so it's at the top
                    history.push(infocontext.code);
                }
                while (history.length > 5) {
                    history.shift();
                }
                setStorage("trackingcodehistory", JSON.stringify(history));

                if (refresh) {
                    router.navigate("/toolbox/track/info", {
                        context: infocontext,
                        reloadCurrent: true
                    });
                } else {
                    router.navigate("/toolbox/track/info", {
                        context: infocontext
                    });
                }
            } else {
                app.dialog.alert(resp.message, "Error");
            }
        },
        error: function (jqXHR, status, errorThrown) {
            if (trackingdialogopen) {
                app.dialog.close();
                trackingdialogopen = false;
            }
            requestfinished = true;
            app.dialog.alert("There was a network issue while tracking the item.  Please try again.", "Error");
        }
    });

    // Open a loading message if there's a delay or we're refreshing the page
    if (refresh) {
        app.dialog.preloader("Tracking...");
        trackingdialogopen = true;
    } else {
        setTimeout(function () {
            if (!requestfinished) {
                app.dialog.preloader("Tracking...");
                trackingdialogopen = true;
            }
        }, 750);
    }
}

function scanTrackingBarcode() {
    scanBarcode(function (code) {
        playSound("scan");
        if (code != "" && code.length > 5) {
            openTrackingHistory(code);
        } else {
            app.dialog.alert("That's not a valid tracking code.", "Error");
        }
    }, function (error) {
        app.dialog.alert(error, "Error");
    });
}

$("#trackbtn").click(function () {
    var code = $("input[name=trackingcode]").val();

    if (code != "" && code.length > 5) {
        openTrackingHistory(code);
    } else {
        app.dialog.alert("That's not a valid tracking code.", "Error");
    }
});

$("input[name=trackingcode]").on('keypress', function (e) {
    if (event.key === "Enter") {
        $("#trackbtn").click();
    }
});