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

function createMap() {
    if (mapboxgl.supported()) {
        $("#mapbox").css("display", "");
        map = maplibreMap();
    } else {
        console.log("maplibre-gl not supported, disabling map");
        $("#mapbox").css("display", "none");
    }
}

function centerMapOnLocation(latitude, longitude) {
    map.removeMarkers();
    map.addMarker(latitude, longitude);
    map.animateMapIn(latitude, longitude, 16);
}

/**
 * Destroy and re-create the map.
 * @returns {undefined}
 */
function reloadMap() {
    try {
        if (map != null && typeof map != 'undefined') {
            map.off();
            map.remove();
            map = null;

            createMap();
        } else {
            createMap();
        }
    } catch (ex) {
        // oh well ¯\(°_o)/¯
        console.log(ex);
        $("#mapbox").css("display", "none");
    }
}

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 = 1;
    }
    if (typeof heading == 'undefined') {
        heading = 0;
    }
    map.animateMapIn(latitude, longitude, zoom, heading);
}