{% 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 %}
<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.last_login 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.last_login and 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 %}
{% endblock %}


{% block scripts %}
{{ super() }}
{{ moment.include_moment() }}
<script type="text/javascript" , crossorigin="anonymous">
    // Leaflet Map
    '{% set last_location = player.last_location() %}'
    var map = L.map('map', {
        center: ['{{ last_location.latitude or 52.2 }}', '{{ last_location.longitude or 5.3 }}'],
        minZoom: 6,
        maxZoom: 19,
        bounds: [
            [50.5, 3.25],
            [54, 7.6]
        ],
        zoom: 9
    });
    L.control.scale().addTo(map);

    L.tileLayer(
        'https://geodata.nationaalgeoregister.nl/tiles/service/wmts/brtachtergrondkaartpastel/EPSG:3857/{z}/{x}/{y}.png', {
            attribution: 'Kaartgegevens &copy; <a href="https://kadaster.nl">Kadaster</a>'
        }).addTo(map);

    var greenIcon = new L.Icon({
        iconUrl: "{{ url_for('static', filename='assets/leaflet/images/marker-icon-2x-green.png') }}",
        shadowUrl: "{{ url_for('static', filename='assets/leaflet/images/marker-shadow.png') }}",
        iconSize: [25, 41],
        iconAnchor: [12, 41],
        popupAnchor: [1, -34],
        shadowSize: [41, 41]
    });

    var locations = JSON.parse('{{ json.dumps(player.locations_during_game(), cls=location_encoder)|safe }}')
    if (locations == null) {
        locations = []
    }
    for (var i = 0; i < locations.length; i++) {
        var playerMarker = L.marker([
            locations[i]['latitude'],
            locations[i]['longitude']
        ], {
            icon: greenIcon
        }).addTo(map);
        var timestamp_utc = moment.utc(locations[i]['timestamp_utc']).toDate()
        var timestamp_local = moment(timestamp_utc).local().format('YYYY-MM-DD HH:mm');
        playerMarker.bindTooltip(`<b>${locations[i]['username']}</b><br>
                                    ${timestamp_local}`).openPopup();
    }

    if (locations.length > 0) {
        var polyline = L.polyline(locations.map(l => [l.latitude, l.longitude]), {
            color: 'red'
        }).addTo(map);
        // zoom the map to the polyline
        map.fitBounds(polyline.getBounds());
    }

    //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 %}