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

mapboxgl.accessToken = '';
const map = new mapboxgl.Map({
    container: 'mapbox',
    style: SETTINGS['map_style_json'],
    attributionControl: false,
    dragPan: false,
    pitch: 0,
    zoom: 0,
    maxZoom: 20
});

var dpPoint = null;
var dpPitch = null;

map.on('touchstart', function (data) {
    if (data.points.length == 2) {
        var diff = Math.abs(data.points[0].y - data.points[1].y);
        if (diff <= 50) {
            dpPoint = data.point;
            map.touchZoomRotate.disable();
            dpPitch = map.getPitch();
        }
    }
});

map.on('touchmove', function (data) {
    if (dpPoint) {
        data.preventDefault();
        var pitchdiff = (dpPoint.y - data.point.y) * 0.5;
        map.setPitch(dpPitch + pitchdiff);
    }
});

map.on('touchend', function (data) {
    if (dpPoint) {
        map.touchZoomRotate.enable();
    }
    dpPoint = null;
    dpPitch = null;
});

map.on('touchcancel', function (data) {
    if (dpPoint) {
        map.touchZoomRotate.enable();
    }
    dpPoint = null;
    dpPitch = null;
});

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

var gotfirstfix = false;

var geoerrorcount = 0;

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) {
    if (typeof heading == 'number') {
        map.easeTo({
            bearing: heading,
            easing: mapEasing
        });
    }
}

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

function updatePlaceLayer(latitude, longitude) {
    callAPI("nearbyplaces", {
        username: localStorage.getItem("username"),
        password: localStorage.getItem("password"),
        latitude: latitude,
        longitude: longitude,
        radius: 5
    }, function (data) {
        var oldmarkers = document.getElementsByClassName("place-marker");
        if (oldmarkers.length > 0) {
            markerparent = oldmarkers[0].parentNode;
            while (oldmarkers.length > 0) {
                markerparent.removeChild(oldmarkers[0]);
            }
        }
        data.features.forEach(function (place) {
            var el = document.createElement("div");
            el.className = "place-marker";
            if (place.properties.teamid != null && place.properties.teamid > 0) {
                el.className += " color-filter-" + SETTINGS["teams"][place.properties.teamid]["color"];
            }

            el.addEventListener('click', function () {
                window.alert(place.properties.name + " \n" + place.properties.id);
            });

            new mapboxgl.Marker(el)
                    .setLngLat(place.geometry.coordinates)
                    .addTo(map);
        });
    });
}

function animateMapIn(latitude, longitude, zoom, heading) {
    if (typeof zoom == 'undefined') {
        zoom = 17;
    }
    if (typeof heading == 'undefined') {
        heading = 0;
    }
    map.flyTo({
        center: [
            longitude,
            latitude
        ],
        speed: 0.7,
        zoom: zoom,
        heading: heading,
        pitch: 45
    });
    // Set min zoom after some time to fly in
    setTimeout(function () {
        map.setMinZoom(16);
        map.setPitch(45);
    }, 1000);
}