{% extends "base.html" %}
{% import 'bootstrap/wtf.html' as wtf %}

{% block head %}
{{ super() }}
<link rel="stylesheet" href="{{ url_for('static', filename='assets/leaflet/leaflet.css') }}" />
<script src="{{ url_for('static', filename='assets/leaflet/leaflet.js') }}"></script>
{% endblock %}

{% block app_content %}
<meta name="csrf-token" content="{{ csrf_token() }}">
<h1>Player: {{ player.user.name }}</h1>
<hr>
<div class="row">
    <div class="col-md-4 col-sm-6 col-xs-8">
        <div class="row">
            {{ wtf.quick_form(form, button_map={'submit': 'primary'}) }}
        </div>

        {% if player.user.auth_hash and not player.user.password_hash %}
        <div class="row">
            <a href="{{ url_for('auth.user_hash_login', auth_hash=player.user.auth_hash) }}">
                <img src="{{ url_for('auth.user_qrcode', auth_hash=player.user.auth_hash) }}" alt="qr_code_failed" width="80%" title="login code for {{ player.user.name }}">
            </a>     
        </div>
        {% elif not player.user.password_hash %}
        <br>
        <div class="row">
            <a href="#" , id="generate_auth_hash">
                <button class="btn btn-success">Generate Login Code</button></a>
        </div>
        {% endif %}
    </div>
    <div id="map" style=" height: 400px; border-radius: 10px; " class="col-md-6 col-xs-12"></div>
</div>
{% if player.caught_players %}
<div class="row">
    <h2>Caught Players:</h2>
    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th scope="col">Player Name</th>
                    <th scope="col">Review</th>
                    <th scope="col">Time</th>
                    <th scope="col"></th>
                </tr>
            </thead>
            <tbody>
                {% for pcp in player.player_caught_players %}
                <tr>
                    <td><a
                            href="{{ url_for('main.game_player', game_name=player.game.name, username = pcp.caught_player.user.name) }}">{{ pcp.caught_player.user.name }}</a>
                    </td>
                    <td>{{ pcp.review.name.title() }}</td>
                    <td>{{ moment(pcp.timestamp).fromNow() }}</td>
                    <td><a href="{{ url_for('main.caught_bunny_photo', 
                                            game_name=player.game.name, 
                                            timestamp=pcp.timestamp.strftime('%Y%m%d%H%M%S'), 
                                            bunny_name=pcp.caught_player.user.name,
                                            hunter_name=pcp.catching_player.user.name) }}">
                            <button class="btn btn-primary">Photo</button></a>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
</div>
{% endif %}

{% if player.player_found_objectives %}

<div class="row">
    <h2>Found Objectives:</h2>
    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th scope="col">Objective name</th>
                    <th scope="col">Time</th>
                    <th scope="col">Coordiates</th>
                </tr>
            </thead>
            <tbody>
                {% for pfo in player.player_found_objectives %}
                <tr>
                    <td>{{ pfo.objective.name }}</td>
                    <td>{{ moment(pfo.timestamp).fromNow() }}</td>
                    <td>{{ pfo.objective.latitude }}, {{ pfo.objective.longitude }}</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
</div>
{% endif %}
{% endblock %}


{% block scripts %}
{{ super() }}
<script src="{{ url_for('static', filename='assets/leaflet/utils.js') }}"></script>
<script type="text/javascript" , crossorigin="anonymous">
    // Leaflet Map
    map = getMap()

    var locations = JSON.parse('{{ json.dumps(player.locations_during_game(), cls=location_encoder)|safe }}')
    if (locations == null) {
        locations = [];
    }

    var markers = [];
    var lastMarker;
    updateMarkers();
    var polyline;
    updatePolyline();
    
    // zoom the map to the polyline
    if(polyline != undefined){
        map.fitBounds(polyline.getBounds(), {
            maxZoom : 13
        });
    }

    function updateMarkers(){
        if(markers != undefined){
            markers.forEach(function(marker){
                marker.remove()
            });
            markers = []
        }
        if(locations.length == 0){ return }
        for (var i = 0; i < locations.length -1; i++) {
            markers.push(addPlayerMarker(map, locations[i], bluePlayerIconMini))
        }
        if(lastMarker != undefined){
            lastMarker.remove()
        }
        lastMarker = addPlayerMarker(map, locations[locations.length-1], bluePlayerIcon)
    }

    function updatePolyline(){
        if(polyline != undefined){
            map.removeLayer(polyline)
        }
        if (locations.length == 0) { return }
        polyline = L.polyline(locations.map(l => [l.latitude, l.longitude]), {
            color: 'blue',
            opacity: 0.6,
        }).addTo(map);
    }
    
    // Poll Locations
        
    setInterval(function() {
        pollLocations(
            "{{ url_for('main.poll_locations', game_name=player.game.name) }}",
            ['{{ player.user.name }}'],
            'accumulative',
            locations,
            handleResponse
            )}, 30 * 1000);

    function handleResponse(data){
        data.forEach(function (location) {
            if (location.username == '{{ player.user.name }}' && new Date(location.timestamp_utc) > get_latest_date(locations) ){
                lastLocation = locations[locations.length-1]
                if (lastLocation.latitude == location.latitude && lastLocation.longitude == location.longitude){
                    lastLocation.timestamp_utc = location.timestamp_utc
                } else{
                    locations.push(location)
                }
            }
        });
        updatePolyline()
        updateMarkers()
    }
    //Ajax for Generate Code button
    $(function () {
        $('a#generate_auth_hash').bind('click', function () {
            $.ajax({
                url: "{{ url_for('auth.generate_auth_hash', username=player.user.name) }}",
                success: function (result) {
                    location.reload();
                }
            });
        });
    });
</script>
{% endblock %}