/*
 * 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: 12,
        maxZoom: 16,
        zoom: 13,
        center: L.latLng(46.5966, -112.0180),
        maxBounds: L.latLngBounds(L.latLng(46.7384, -112.1429), L.latLng(46.5127, -111.7557)),
        //maxBounds: L.latLngBounds(L.latLng(46.9, -112.3), L.latLng(46.35, -111.5)),
        attributionControl: false
    });

    L.tileLayer('assets/tiles/{z}/{x}/{y}.png', {
        minZoom: 12,
        maxZoom: 16,
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);

    map.locateControl = L.control.locate({
        flyTo: true,
        icon: "far fa-compass",
        iconLoading: "far fa-compass fa-spin"
    }).addTo(map);

    map.packagelayer = L.layerGroup();

    map.packagelayer.addTo(map);

    map.setView({lat: 0, lng: 0}, 1);

    map.setMapHeading = function (heading) {

    }

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

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

        data.forEach(function (package) {

            var iconName = "box";

            if (package.delivered) {
                iconName = "box-check";
            } else if (package.distance * 1 < localStorage.getItem("alertradius") * 1) {
                iconName = "box-alert";
            }

            var icon = L.icon({
                iconUrl: "assets/images/" + iconName + ".png",
                iconSize: [25, 25],
                iconAnchor: [12.5, 12.5]
            });

            L.marker(
                    [
                        package.coords[0],
                        package.coords[1]
                    ],
                    {
                        icon: icon
                    })
                    .on('click', function () {
                        openPackageInfoSheet(package);
                    })
                    .addTo(map.packagelayer);
        });
    }

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