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

var maptype = "mapbox";

function createMap() {
    if (getStorage("maptype") == null) {
        setStorage("maptype", "mapbox");
    }
    maptype = getStorage("maptype");
    if (maptype == "mapbox") {
        if (mapboxgl.supported()) {
            map = mapboxMap();
        } else {
            console.log("Warn", "mapbox-gl not supported, falling back to Leaflet");
            maptype = "leaflet";
            map = leafletMap();
        }
    } else {
        map = leafletMap();
    }
    map.updatePackageLayer(packages);
}

/**
 * Destroy and re-create the map.
 * @returns {undefined}
 */
function reloadMap() {
    try {
        if (map != null && typeof map != 'undefined') {
            var mapcenter = map.getCenter();
            var mapzoom = map.getZoom();
            if (map.maptype == "mapbox") {
                var mapbearing = map.getBearing();
                var mappitch = map.getPitch();
            }

            map.off();
            map.remove();
            map = null;

            if (document.getElementById("mapbox") != null) {
                createMap();

                if (map.maptype == "mapbox") {
                    map.jumpTo({
                        center: mapcenter,
                        zoom: mapzoom,
                        bearing: mapbearing,
                        pitch: mappitch
                    });
                } else {
                    map.setView(mapcenter, mapzoom);
                }
            } else {
                console.log("Info", "Not re-creating map because #mapbox is not in DOM. Creation will be automatically triggered when map page is loaded.");
            }
        } else {
            createMap();
        }
    } catch (ex) {
        // oh well ¯\(°_o)/¯
        console.log(ex);
    }
}

$("#app").on("click", "#package-info-sheet #package-info-sheet-inner .list ul li .item-content", function () {
    markDelivered($(this).data("id"));
    map.updatePackageLayer(packages);
    openPackageInfoSheet($(this).data("coordid"), true);
});

$("#app").on("sheet:close", "#package-info-sheet", function () {
    map.openedPanelIconID = null;
    $(".package-marker").removeClass("selected");
});

$("#app").on("click", "#package-info-sheet #package-info-deliver-all", function () {
    var coordid = $(this).data("coordid");
    for (var i = 0; i < packages.length; i++) {
        if (packages[i].id == coordid) {
            package = packages[i];
            for (var j = 0; j < package.items.length; j++) {
                if (package.items[j].delivered) {
                    continue;
                }
                markDelivered(package.items[j].id, true);
            }
            break;
        }
    }
    map.updatePackageLayer(packages);
    openPackageInfoSheet(coordid, true);
});

function openPackageInfoSheet(coordid, refreshOnly) {
    map.openedPanelIconID = coordid;
    if (typeof refreshOnly == "undefined") {
        refreshOnly = false;
    }

    //console.log("Packages array: ", packages);

    $(".package-marker").removeClass("selected"); // prevent multiple highlights when switching icons in tablet mode
    $(".package-marker#marker-" + coordid).addClass("selected");

    for (var i = 0; i < packages.length; i++) {
        if (packages[i].id == coordid) {
            package = packages[i];
            //console.log("Single Address:", package);

            $("#package-info-get-directions").attr("href", "geo:" + package.coords[0] + "," + package.coords[1]);
            $("#package-info-sheet-inner .list ul").html("");
            $("#package-info-deliver-all").data("coordid", coordid);

            for (var j = 0; j < package.items.length; j++) {
                var classes = "";
                var icon = getIconForType(package.items[j].type);
                var statusicon = "far fa-circle";
                if (package.items[j].delivered) {
                    classes = "text-color-green";
                    statusicon = "far fa-check-circle";
                }
                $("#package-info-sheet-inner .list ul").append(''
                        + '<li>'
                        + '    <div class="item-content ' + classes + '" data-id="' + package.items[j].id + '" data-coordid="' + package.id + '">'
                        + '        <div class="item-media"><i class="' + statusicon + '"></i></div>'
                        + '        <div class="item-inner">'
                        + '            <div class="item-title">' + package.items[j].address + '</div>'
                        + '            <div class="item-after"><i class="' + icon + '"></i></div>'
                        + '        </div>'
                        + '    </div>'
                        + '</li>');
            }

            if (!refreshOnly) {
                app.sheet.create({el: "#package-info-sheet"}).open();
            }
            break;
        }
    }
}

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);
}