/*
 * 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 map = null;

function createMap() {
    map = leafletMap();
    map.updatePackageLayer(packages);
}

/**
 * Make the toggle button on the popup sheet do things
 */
$("#app").on("click", "#package-info-sheet #package-info-toggle-status", 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));
        map.updatePackageLayer(packages);
        openPackageInfoSheet(packages[pid], true);
    } else {
        app.dialog.confirm(
                packages[pid].address,
                "Mark Undelivered",
                function () {
                    // undeliver
                    packages[pid].delivered = false;
                    localStorage.setItem("packages", JSON.stringify(packages));
                    map.updatePackageLayer(packages);
                    openPackageInfoSheet(packages[pid], true);
                },
                function () {
                    // cancel
                }
        );
    }
});

function openPackageInfoSheet(package, refreshOnly) {
    if (typeof refreshOnly == "undefined") {
        refreshOnly = false;
    }
    $("#package-info-toggle-status").data("packageid", packages.findIndex(function (p) {
        return p == package;
    }));
    $("#package-info-address").text(package.address);
    if (package.delivered) {
        $("#package-info-delivery-status").html('<span class="text-color-green"><i class="fas fa-check-circle"></i> Delivered</span>');
        $("#package-info-toggle-status").text("Mark undelivered");
    } else {
        $("#package-info-delivery-status").html('<i class="fas fa-circle"></i> Not delivered');
        $("#package-info-toggle-status").text("Mark delivered");
    }
    if (!refreshOnly) {
        app.sheet.create({el: "#package-info-sheet"}).open();
    }
}

function setMapLocation(latitude, longitude) {
    if (map == null) {
        return;
    }
    map.setMapLocation(latitude, longitude);
}

function animateMapIn(latitude, longitude, zoom, heading) {
    if (map == null) {
        return;
    }
    if (typeof zoom == 'undefined') {
        zoom = 14;
    }
    if (typeof heading == 'undefined') {
        heading = 0;
    }
    map.animateMapIn(latitude, longitude, zoom, heading);
}