{% extends 'base.html' %}

{% block app_content %}
    <meta name="csrf-token" content="{{ csrf_token() }}">
    {% block player_app_content %}{% endblock %}
{% endblock %}

{% block scripts %}
{{ super() }}
<script>
var csrftoken = $('meta[name=csrf-token]').attr('content')
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken)
        }
    }
})

function sendLocation(position) {
    $.ajax({
        type: "POST",
        url: "{{ url_for('main.send_location', username=current_user.name) }}",
        data:{
            lat: position.coords.latitude, 
            long: position.coords.longitude
        },
        
        error: function(error) {
            console.log(error);
        }
    });
}

function showError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            console.log("User denied the request for Geolocation.")
            break;
        case error.POSITION_UNAVAILABLE:
            console.log("Location information is unavailable.")
            break;
        case error.TIMEOUT:
            console.log("The request to get user location timed out.")
            break;
        case error.UNKNOWN_ERROR:
            console.log("An unknown error occurred.")
            break;
    }
} 

$(document).ready(function(){
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(sendLocation, showError);
    
    } else {
        console.log('Geolocation is not supported by this browser.')
    }
})

</script>
{% endblock %}