/*
 * 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() {

    /* Pre-load workers and stuff, and enable re-using them even after map unloaded */
    maplibregl.prewarm();

    var mapsource = "auto";

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

    if (mapsource == "auto") {
        if ($("#app").hasClass("theme-dark")) {
            mapsource = "libertydark";
        } else {
            mapsource = "liberty";
        }
    }

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

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

    map.maptype = "mapbox";

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

    map.addControl(
            new maplibregl.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 maplibregl.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 hapticbtn";
                // 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 maplibregl.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;
}