/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

$(".view-main").on("click", "#addresslist .package-list-item .item-content", function () {
    var pid = $(this).data("packageid");
    if (typeof packages[pid].delivered == "undefined" || packages[pid].delivered == false) {
        packages[pid].delivered = true;
        localStorage.setItem("packages", JSON.stringify(packages));
        loadPackageList();
    } else {
        app.dialog.confirm(
                packages[pid].address,
                "Mark Undelivered",
                function () {
                    // undeliver
                    packages[pid].delivered = false;
                    localStorage.setItem("packages", JSON.stringify(packages));
                    loadPackageList();
                },
                function () {
                    // cancel
                }
        );
    }
});

$(".view-main").on("mousedown", "#addresslist .package-list-item .item-content", function (e) {
    if (e.button == 2) {
        confirmDeletePackage($(this).data("packageid"));
    }
});

$(".view-main").on("swipeout:delete", "#addresslist .package-list-item", function () {
    console.log("Deleting package", $(this).data("packageid"));
    deletePackage($(this).data("packageid"));
});

/**
 * Update package distances relative to the passed coordinates.
 * @param {type} latitude
 * @param {type} longitude
 * @returns {undefined}
 */
function updateDistances(latitude, longitude) {
    for (var i = 0; i < packages.length; i++) {
        var distance = getDistance(latitude, longitude, packages[i].coords[0], packages[i].coords[1]).toFixed(0);
        packages[i].distance = distance;
        $("#addresslist .package-list-item[data-packageid=\"" + i + "\"] .item-content").data("distance", distance);
        $("#addresslist .package-list-item[data-packageid=\"" + i + "\"] .item-content .distance").text(distance + " m");
    }
}

function loadPackageList(sortType) {
    // If no sort type is specified, use the saved pref or a default one
    if (typeof sortType == 'undefined') {
        if (localStorage.getItem("sorttype") == null) {
            localStorage.setItem("sorttype", "distance_asc");
        }
        sortType = localStorage.getItem("sorttype");
    } else {
        // save the current sorting order so it'll stay consistent next time the list is refreshed
        localStorage.setItem("sorttype", sortType);
    }

    updateDistances(userPosition.coords.latitude, userPosition.coords.longitude);

    var sortedPackages = packages.map(function (el, i) {
        return {index: i, value: el};
    });

    sortedPackages.sort(function (a, b) {
        var aalpha = a.value.address.substr(a.value.address.indexOf(' ') + 1);
        var balpha = b.value.address.substr(b.value.address.indexOf(' ') + 1);
        var anum = parseInt(a.value.address.split(" ", 1)[0], 10);
        var bnum = parseInt(b.value.address.split(" ", 1)[0], 10);

        console.log("aalpha", aalpha);
        console.log("balpha", balpha);
        switch (sortType) {
            case "alpha_desc":
                if (aalpha > balpha) {
                    return -1;
                } else if (aalpha < balpha) {
                    return 1;
                }
                return 0;
            case "alpha_asc":
                if (aalpha > balpha) {
                    return 1;
                } else if (aalpha < balpha) {
                    return -1;
                }
                return 0;
            case "number_desc":
                return bnum - anum;
            case "number_asc":
                return anum - bnum;
            case "distance_desc":
                return b.value.distance - a.value.distance;
            case "distance_asc":
            default:
                return a.value.distance - b.value.distance;
        }

    });

    $("#addresslist").html("");

    for (var i = 0; i < sortedPackages.length; i++) {
        var icon = "fas fa-box-open";
        var classes = "";
        if (sortedPackages[i].value.delivered == true) {
            icon = "fas fa-check";
            classes = "text-color-green";
        } else if (typeof sortedPackages[i].value.distance != 'undefined' && sortedPackages[i].value.distance * 1 < localStorage.getItem("alertradius") * 1) {
            classes = "text-color-deeporange";
        }
        $("#addresslist").append(
                '<li class="swipeout package-list-item" data-packageid="' + sortedPackages[i].index + '">'
                + '<div class="item-content swipeout-content ' + classes + '" data-packageid="' + sortedPackages[i].index + '" data-latitude="' + sortedPackages[i].value.coords[0] + '" data-longitude="' + sortedPackages[i].value.coords[1] + '">'
                + '  <div class="item-media">'
                + '    <i class="icon ' + icon + '"></i>'
                + '  </div>'
                + '  <div class="item-inner">'
                + '    <div class="item-title">'
                + '       ' + sortedPackages[i].value.address
                + '    </div>'
                + '    <div class="item-footer">'
                + '      <span class="distance">' + (typeof sortedPackages[i].value.distance != 'undefined' ? sortedPackages[i].value.distance : '...') + ' m</span>'
                + '    </div>'
                + '  </div>'
                + '</div>'
                + '<div class="swipeout-actions-right">'
                + '  <a href="#" class="swipeout-delete">Delete</a>'
                + '</div>'
                + '</li>'
                );
    }
}

function confirmDeleteAllPackages() {
    app.dialog.confirm(
            "Really delete all packages from list?",
            "Clear Packages",
            function () {
                // clear
                packages = [];
                localStorage.setItem("packages", JSON.stringify(packages));
                loadPackageList();
                if (map != null) {
                    map.updatePackageLayer(packages);
                }
            },
            function () {
                // cancel
            }
    );
}