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

function leafletMap() {
    var map = L.map('mapbox', {
        zoomSnap: 0.25,
        minZoom: 1,
        maxZoom: 19,
        zoom: 12,
        center: L.latLng(46.5966, -112.0180),
        attributionControl: false
    });

    map.maptype = "leaflet";

    if (getStorage("mapsource") == null) {
        setStorage("mapsource", "liberty");
    }

    $("#mapbox").css("background-color", SETTINGS.maptileurls[getStorage("mapsource")].bgcolor);

    L.tileLayer(SETTINGS.maptileurls[getStorage("mapsource")].url, {
        minZoom: 1,
        maxZoom: 19
    }).addTo(map);

    map.locateControl = L.control.locate({
        flyTo: false, // Hopefully this will lower the number of map tile requests when location is found
        showPopup: false,
        locateOptions: {
            enableHighAccuracy: true,
            maxZoom: getStorage("trackzoom") == null ? 16 : getStorage("trackzoom") * 1
        },
        setView: "untilPanOrZoom",
        icon: "far fa-compass",
        iconLoading: "far fa-compass fa-spin"
    }).addTo(map);

    map.packagelayer = L.markerClusterGroup();

    map.packagelayer.addTo(map);

    map.setView({lat: userPosition.coords.latitude, lng: userPosition.coords.longitude}, 2);

    map.startLocateControl = function () {
        map.locateControl.start();
    }

    map.stopLocateControl = function () {

    }

    map.setMapHeading = function (heading) {

    }

    map.setMapLocation = function (latitude, longitude) {
        map.setView({
            lng: longitude,
            lat: latitude
        });
    }

    map.openedPanelIconID = null;

    map.updatePackageLayer = function (data) {
        map.packagelayer.clearLayers();

        //console.log(data);

        for (var i = 0; i < data.length; i++) {
            // JavaScript variable scope and anonymous functions are dumb
            // This is necessary, otherwise all the on(click)s will fire for the last iteration
            // of the loop, or something like that
            (function (datai) {
                var iconName = getMapIconForItems(datai.items);
                //console.log(iconName);

                var classes = "package-marker package-marker-leaflet";

                // Prevent selection highlight from going away after map refresh
                if (map.openedPanelIconID != null && map.openedPanelIconID == datai.id) {
                    classes += " selected";
                }
                // Show different color highlight when nearby and undelivered
                if (packages[i].distance * 1 < getStorage("alertradius") * 1
                        && getUndeliveredCount(packages[i]) > 0) {
                    classes += " alerted";
                }
                var icon = L.icon({
                    iconUrl: "assets/images/" + iconName + ".png",
                    iconSize: [25, 25],
                    iconAnchor: [12.5, 12.5],
                    className: classes
                });

                var marker = L.marker(
                        [
                            datai.coords[0],
                            datai.coords[1]
                        ],
                        {
                            icon: icon,
                        })
                        .on("click", function () {
                            marker._icon.id = "marker-" + datai.id;
                            openPackageInfoSheet(datai.id);
                        });

                map.packagelayer.addLayer(marker);

                //L.DomUtil.addClass(marker._icon, 'package-marker'); // enable selected CSS to work correctly
            })(data[i]);
        }
    }

    map.animateMapIn = function (latitude, longitude, zoom, heading) {
        if (typeof zoom == 'undefined') {
            zoom = 14;
        }
        if (typeof heading == 'undefined') {
            heading = 0;
        }
        map.flyTo([latitude, longitude], zoom);
        // Set min zoom after some time to fly in
        setTimeout(function () {
            map.setMinZoom(12);
            map.setZoom(zoom);
        }, 1000);
    }

    return map;
}