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

$(".view-main").on("click", "#addresslist .package-list-item .deliver-btn", function () {
    var pid = $(this).data("packageid");
    markDelivered(pid);
    loadPackageList();
});

$(".view-main").on("click", "#addresslist .package-list-item .delete-btn", function () {
    var id = $(this).parents(".package-list-item").data("packageid");
    console.log("Info", "Deleting package", id);
    deletePackage(id);
});

// Searchbar is setup in routes.js, this is for forcing a wider scope
var searchbar = null;

var itemVirtualList = null;

/**
 * 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(getDisplayDistance(distance));
    }
}

function loadPackageList(sortType) {
    // If no sort type is specified, use the saved pref or a default one
    if (typeof sortType == 'undefined') {
        if (getStorage("sorttype") == null) {
            setStorage("sorttype", "distance_asc");
        }
        sortType = getStorage("sorttype");
    } else {
        // save the current sorting order so it'll stay consistent next time the list is refreshed
        setStorage("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 ul").html("");

    if (packages.length == 0) {
        $("#no-packages-display").removeClass("display-none");
    } else {
        $("#no-packages-display").addClass("display-none");
    }

    var items = [];
    for (var i = 0; i < sortedPackages.length; i++) {
        for (var j = 0; j < sortedPackages[i].value.items.length; j++) {
            var item = sortedPackages[i].value.items[j];
            var icon1 = getIconForType(item.type);
            var icon2 = "";
            var classes = "";
            var delivered = false;
            if (item.delivered) {
                delivered = true;
                icon2 = icon1;
                icon1 = "far fa-check-circle fa-fw";
                classes = "text-color-green";
            } else if (typeof sortedPackages[i].value.distance != 'undefined' && sortedPackages[i].value.distance * 1 < getStorage("alertradius") * 1) {
                classes = "text-color-deeporange";
            }
            items.push({
                id: item.id,
                coordid: sortedPackages[i].value.id,
                classes: classes,
                latitude: sortedPackages[i].value.coords[0],
                longitude: sortedPackages[i].value.coords[1],
                icon1: icon1,
                icon2: icon2,
                address: item.address,
                distance: (typeof sortedPackages[i].value.distance != 'undefined' ? getDisplayDistance(sortedPackages[i].value.distance) : '...'),
                delivered: delivered,
                geolink: 'geo:' + sortedPackages[i].value.coords[0] + ',' + sortedPackages[i].value.coords[1]
            });
        }
    }

    itemTemplateAccordion = '<li class="package-list-item accordion-item" data-packageid="{{id}}" data-coordid="{{coordid}}">'
            + '<div class="item-content item-link {{classes}}" data-packageid="{{id}}" data-latitude="{{latitude}}" data-longitude="{{longitude}}">'
            + '  <div class="item-inner">'
            + '    <div class="item-title">'
            + '       <i class="{{icon1}}"></i>'
            + '       {{address}}'
            + '    </div>'
            + '    <div class="item-footer">'
            + '      <i class="{{icon2}}"></i>'
            + '      <span class="distance">{{distance}}</span>'
            + '    </div>'
            + '  </div>'
            + '</div>'
            + '<div class="accordion-item-content">'
            + '  <div class="row padding-horizontal">'
            + '    <a href="#" class="col deliver-btn button button-outline color-green" data-packageid="{{id}}">{{#if delivered}}<i class="fas fa-undo"></i> Undeliver{{else}}<i class="fas fa-check"></i>&nbsp; Deliver{{/if}}</a>'
            + '    <a href="{{geolink}}" class="col geolink directions-btn button button-outline"><i class="fas fa-directions"></i> Directions</a>'
            + '    <a href="#" class="col delete-btn color-red button button-outline"><i class="fas fa-trash"></i> Delete</a>'
            + '  </div>'
            + '  </div>'
            + '</div>'
            + '</li>';

    itemTemplateSwipe = '<li class="swipeout package-list-item" data-packageid="{{id}}" data-coordid="{{coordid}}">'
            + '<div class="item-content swipeout-content {{classes}}" data-packageid="{{id}}" data-latitude="{{latitude}}" data-longitude="{{longitude}}">'
            + '  <div class="item-media {{classes}}">'
            + '    <i class="icon {{icon1}}"></i>'
            + '  </div>'
            + '  <div class="item-inner">'
            + '    <div class="item-title">'
            + '       {{address}}'
            + '    </div>'
            + '    <div class="item-footer">'
            + '      <span class="distance">{{distance}}</span>'
            + '    </div>'
            + '  </div>'
            + '</div>'
            + '<div class="swipeout-actions-left">'
            + '  <a href="#" class="color-green deliver-btn" data-packageid="{{id}}">{{#if delivered}}<i class="fas fa-undo"></i> &nbsp; Undeliver{{else}}<i class="fas fa-check"></i>&nbsp; Deliver{{/if}}</a>'
            + '  <a href="{{geolink}}" class="color-blue directions-btn"><i class="material-icons">directions</i></a>'
            + '</div>'
            + '<div class="swipeout-actions-right">'
            + '  <a href="#" class="color-red delete-btn"><i class="material-icons">delete</i>&nbsp; Delete</a>'
            + '</div>'
            + '</li>';


    itemVirtualList = app.virtualList.create({
        el: "#addresslist",
        items: items,
        searchAll: function (query, items) {
            query = query.toLowerCase();
            var found = [];
            for (var i = 0; i < items.length; i++) {
                if (items[i].address.toLowerCase().indexOf(query) >= 0 || query.trim() === '') {
                    found.push(i);
                }
            }
            return found; //return array with mathced indexes
        },
        itemTemplate: (getStorage("liststyle") == "swipe" ? itemTemplateSwipe : itemTemplateAccordion)
    });

    // If there was a search open when the reload was triggered
    if (router.currentRoute.name == "list") {
        var searchboxVal = $(".package-list-searchbar input[type=search]").val();
        if (searchboxVal != "") {
            searchbar.clear();
            searchbar.search(searchboxVal);
        }
    }
}

function confirmDeleteAllPackages() {
    app.dialog.confirm(
            "Really delete all packages from list?",
            "Clear Packages",
            function () {
                // clear
                let count = countPackages();
                let remaining = countRemainingPackages();
                packages = [];
                setStorage("packages", JSON.stringify(packages));
                appendActivityLog("Cleared List", count + " " + (count != 1 ? "items" : "item") + " removed.", (remaining > 0 ? remaining + " " + (remaining != 1 ? "were" : "was") + " not delivered." : ""), "fas fa-trash");
                loadPackageList();
                if (map != null) {
                    map.updatePackageLayer(packages);
                }
            },
            function () {
                // cancel
            }
    );
}