/*
 * 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 gotfirstfix = false;

var geoerrorcount = 0;

var gamemaptype = "mapbox";

if (localStorage.getItem("litemode") == "true") {
    gamemaptype = "leaflet";
}

if (gamemaptype == "leaflet") {
    var map = leafletMap();
} else {
    var map = mapboxMap();
}

watchLocation(function (position) {
    if (gotfirstfix) {
        setMapLocation(position.coords.latitude, position.coords.longitude);
        updatePlaceLayer(position.coords.latitude, position.coords.longitude);
    } else {
        animateMapIn(position.coords.latitude, position.coords.longitude, 16, position.coords.heading);
        gotfirstfix = true;
    }
}, function (error) {
    geoerrorcount++;
    console.log("Geolocation error #" + geoerrorcount + ": ", error);
    // Stop showing error toasts if they're happening a lot
    if (geoerrorcount > 3) {
        return;
    }
    app.toast.show({
        text: '<i class="fas fa-compass"></i> ' + error,
        position: "bottom",
        destroyOnClose: true,
        closeTimeout: 1000 * 4
    });
});

function setMapHeading(heading) {
    map.setHeading(heading);
}

function setMapLocation(latitude, longitude) {
    map.setMapLocation(latitude, longitude);
}

function updatePlaceLayer(latitude, longitude) {
    callAPI("nearbyplaces", {
        username: localStorage.getItem("username"),
        password: localStorage.getItem("password"),
        latitude: latitude,
        longitude: longitude,
        radius: 5
    }, function (data) {
        map.updatePlaceLayer(data);
    });
}

function animateMapIn(latitude, longitude, zoom, heading) {
    if (typeof zoom == 'undefined') {
        zoom = 17;
    }
    if (typeof heading == 'undefined') {
        heading = 0;
    }
    map.animateMapIn(latitude, longitude, zoom, heading);
}