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

// If true, we'll do a fancy zoom/pan in
// Otherwise we'll just jump to the correct location
var firstload = true;

function mapboxMap() {

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

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

    mapboxgl.accessToken = '';
    var map = new mapboxgl.Map({
        container: 'mapbox',
        style: SETTINGS.maptileurls[getStorage("mapsource")].json,
        //attributionControl: false,
        dragPan: true,
        pitch: 0,
        zoom: 2,
        maxZoom: 19
    });

    map.maptype = "mapbox";

    map.addControl(new mapboxgl.NavigationControl({
        visualizePitch: true
    }), 'top-left');

    map.addControl(
            new mapboxgl.GeolocateControl({
                positionOptions: {
                    enableHighAccuracy: true,
                    timeout: 10 * 1000
                },
                fitBoundsOptions: {
                    maxZoom: getStorage("trackzoom") == null ? 16 : getStorage("trackzoom") * 1
                },
                trackUserLocation: true
            }), 'top-left'
            );

    if (getStorage("mapscale") !== "false") {
        map.addControl(
                new mapboxgl.ScaleControl({
                    unit: getStorage("units") == "imperial" ? "imperial" : "metric"
                })
                );
    }

    map.startLocateControl = function () {
        // stub
    }

    map.stopLocateControl = function () {
        // stub
    }

    map.mapEasing = function (t) {
        return t * (2 - t);
    }

    map.setMapHeading = function (heading) {
        if (typeof heading == 'number') {
            map.easeTo({
                bearing: heading,
                easing: map.mapEasing
            });
        }
    }

    map.setMapLocation = function (latitude, longitude) {
        map.easeTo({
            center: [
                longitude,
                latitude
            ]
        });
    }

    map.openedPanelIconID = null;

    map.updatePackageLayer = function (data) {
        var oldmarkers = document.getElementsByClassName("package-marker");
        if (oldmarkers.length > 0) {
            markerparent = oldmarkers[0].parentNode;
            while (oldmarkers.length > 0) {
                markerparent.removeChild(oldmarkers[0]);
            }
        }

        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 el = document.createElement("div");

                el.className = "package-marker package-marker-mapbox";
                // Prevent selection highlight from going away after map refresh
                if (map.openedPanelIconID != null && map.openedPanelIconID == datai.id) {
                    el.className += " selected";
                }
                // Show different color highlight when nearby and undelivered
                if (packages[i].distance * 1 < getStorage("alertradius") * 1
                        && getUndeliveredCount(packages[i]) > 0) {
                    el.className += " alerted";
                }

                el.id = "marker-" + datai.id;

                el.style = "background-image: url(assets/images/" + iconName + ".png);";

                el.addEventListener('click', function () {
                    openPackageInfoSheet(datai.id);
                });

                new mapboxgl.Marker(el)
                        .setLngLat([datai.coords[1], datai.coords[0]])
                        .addTo(map);
            })(data[i]);
        }
    }

    map.animateMapIn = function (latitude, longitude, zoom, heading) {
        if (typeof zoom == 'undefined') {
            zoom = 16;
        }
        if (typeof heading == 'undefined') {
            heading = 0;
        }
        map.flyTo({
            center: [
                longitude,
                latitude
            ],
            speed: 1,
            zoom: zoom,
            heading: heading,
            pitch: 0
        });
    }

    map.animateMapIn(userPosition.coords.latitude, userPosition.coords.longitude, 12);

    return map;
}