{% extends 'base.html.j2' %}
{% set active_page = "profile" %}

{% block content %}
<div class="container mt-3">
    <div class="row">
        <div class="col">
            <h1 class="display-6">Mijn profiel</h1>
            <p>
                Op je profiel kun je je gegevens invullen. Alle velden zijn optioneel.
                {# Je kunt ook aangeven dat je je gegevens alleen met bepaalde gebruikers wilt
                delen; voor niet-geselecteerde gebruikers zal het lijken alsof je de niet-gedeelde gegevens niet hebt
                ingevuld. #}
            </p>
            {% with successes = get_flashed_messages(category_filter=["success"]) %}
            {% if successes %}
            {% for msg in successes %}
            <div class="alert alert-success" role="alert">
                {{ msg }}
            </div>
            {% endfor %}
            {% endif %}
            {% endwith %}
            <form method="post" action="{{ url_for('profile') }}">
                <input type="hidden" name="_csrf_token" value="{{ csrf_token() }}">
                <div class="row">
                    <label for="input-firstname" class="col-md-2 col-sm-4 col-form-label text-sm-end">Voornaam</label>
                    <div class="col-md-4 col-sm-8 mb-sm-3">
                        <input type="text" class="form-control" id="input-firstname" name="first_name"
                            value="{{ user.first_name }}">
                    </div>
                    <label for="input-lastname" class="col-md-2 col-sm-4 col-form-label text-sm-end">Achternaam</label>
                    <div class="col-md-4 col-sm-8 mb-sm-3">
                        <input type="text" class="form-control" id="input-lastname" name="last_name"
                            value="{{ user.last_name }}">
                    </div>
                </div>
                <div class="row mb-3">
                    <label for="input-displayname" class="col-md-2 col-sm-4 col-form-label text-sm-end">
                        <span class='d-none d-md-inline d-lg-none'>Weergave</span>
                        <span class='d-inline d-md-none d-lg-inline'>Weergavenaam</span>
                    </label>
                    <div class="col-md-4 col-sm-8">
                        <input type="text" class="form-control" id="input-displayname" disabled
                            value="{{ user.display_name }}">
                        <small class="text-muted">Afkomstig van idm.hashru.nl</small>
                    </div>
                </div>
                <hr class="mb-2 mb-sm-3">
                <div class="row">
                    <label for="input-email" class="col-md-2 col-sm-4 col-form-label text-sm-end">E-mailadres</label>
                    <div class="col-md-4 col-sm-8 mb-md-0 mb-sm-3">
                        <input type="text" class="form-control" id="input-email" name="email" value="{{ user.email }}">
                    </div>
                    <label id="label-phone" for="input-phone" class="col-md-2 col-sm-4 col-form-label text-sm-end">
                        <span class='d-none d-md-inline d-lg-none'>Telefoonnr.</span>
                        <span class='d-inline d-md-none d-lg-inline'>Telefoonnummer</span>
                    </label>
                    <div class="col-md-4 col-sm-8">
                        <input type="text" class="form-control" id="input-phone" name="phone" value="{{ user.phone }}">
                    </div>
                </div>
                {# <div class="row mb-3">
                    <div class="col-sm-10 offset-sm-2">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="contact-whitelist-check">
                            <label class="form-check-label" for="contact-whitelist-check">
                                Contactgegevens alleen tonen aan geselecteerde gebruikers.
                            </label>
                        </div>
                    </div>
                </div> #}
                <hr class="mb-2 mb-sm-3">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <div class="row mb-sm-3">
                            <label for="input-street" class="col-sm-4 col-form-label text-sm-end">Straatnaam</label>
                            <div class="col-sm-8">
                                <input type="text" class="form-control update-latlon" id="input-street" name="street"
                                    value="{{ user.street }}">
                            </div>
                        </div>
                        <div class="row mb-sm-3">
                            <label for="input-number" class="col-sm-4 col-form-label text-sm-end">Huisnummer</label>
                            <div class="col-sm-8">
                                <input type="text" class="form-control update-latlon" id="input-number" name="number"
                                    value="{{ user.number }}">
                            </div>
                        </div>
                        <div class="row mb-sm-3">
                            <label for="input-postal" class="col-sm-4 col-form-label text-sm-end">Postcode</label>
                            <div class="col-sm-8">
                                <input type="text" class="form-control update-latlon" id="input-postal" name="postal"
                                    value="{{ user.postal }}">
                            </div>
                        </div>
                        <div class="row mb-sm-3">
                            <label for="input-city" class="col-sm-4 col-form-label text-sm-end">Woonplaats</label>
                            <div class="col-sm-8">
                                <input type="text" class="form-control update-latlon" id="input-city" name="city"
                                    value="{{ user.city }}">
                            </div>
                        </div>
                        <div class="row">
                            <label for="input-country" class="col-sm-4 col-form-label text-sm-end">Land</label>
                            <div class="col-sm-8">
                                <input type="text" class="form-control update-latlon" id="input-country" name="country"
                                    value="{{ user.country }}">
                            </div>
                        </div>
                        <div class="row">
                            <!-- <label for="input-lat" class="col-sm-4 col-form-label text-sm-end">Latitude</label> -->
                            <div class="col-sm-3">
                                <input type="hidden" class="form-control" id="input-lat" name="lat"
                                    value="{{ user.lat }}">
                            </div>
                            <!-- <label for="input-lon" class="col-sm-2 col-form-label text-sm-end">Longitude</label> -->
                            <div class="col-sm-3">
                                <input type="hidden" class="form-control" id="input-lon" name="lon"
                                    value="{{ user.lon }}">
                            </div>
                        </div>
                        <div class="row">
                            <div class="offset-sm-4">
                                <!-- <small class="text-muted">Coördinaten zijn alleen voor weergave op de kaart.</small> -->
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 pt-3 pt-md-0">
                        <div class='h-100' id="osm-map" style="min-height:18em;"></div>
                    </div>
                </div>

                {# <div class="row mb-3">
                    <div class="col-sm-10 offset-sm-2">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="address-whitelist-check">
                            <label class="form-check-label" for="address-whitelist-check">
                                Adresgegevens alleen tonen aan geselecteerde gebruikers.
                            </label>
                        </div>
                    </div>
                </div> #}
                <hr class="mb-2 mb-sm-3">
                <div class="row mb-3">
                    <label for="input-birthdate" class="col-md-2 col-sm-4 col-form-label text-sm-end">Verjaardag</label>
                    <div class="col-md-4 col-sm-4">
                        <input id="input-birthdate" class="form-control" name="birthdate" type="date"
                            value="{{ user.birthdate }}" />
                    </div>
                </div>
                {# <div class="row mb-3">
                    <div class="col-sm-10 offset-sm-2">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="birthdate-whitelist-check">
                            <label class="form-check-label" for="birthdate-whitelist-check">
                                Verjaardag alleen tonen aan geselecteerde gebruikers
                            </label>
                        </div>
                    </div>
                </div> #}
                {#
                <hr>
                <div class="row mb-3">
                    <div class="col-sm-10 offset-sm-2">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="include-check" name="include_in_views"
                                {% if user.include_in_views or user.include_in_views is none %}checked{% endif %}>
                            <label class="form-check-label" for="include-check">
                                Toon mij op de kaart, in 't adresboek en op de verjaardagskalender.
                            </label>
                        </div>
                    </div>
                </div> #}
                <div class="row mb-3">
                    <div class="col-sm-10 offset-sm-2">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="gdpr-check" required checked>
                            <label class="form-check-label" for="gdpr-check">
                                Ik geef toestemming mijn gegevens op te slaan en te delen binnen de context van
                                adRUsboek.
                            </label>
                            <div class="invalid-feedback">
                                Je moet toestemming geven om je gegevens te verwerken voordat je ze op kunt slaan.
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row col-sm-12 mb-3">
                    <div class="col text-center">
                        {% if user.include_in_views %}
                        <p>
                            Je profiel is voor het laatst bijgewerkt op {{ user.last_updated | datetime_format }}.
                        </p>
                        {% endif %}
                        <button type="submit" class="btn btn-primary">Opslaan</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"></script>
<script type="text/javascript">
    (function () {
        'use strict'

        const tileserver_osm = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png';
        const tileserver_humanitarian = "https://tile.openstreetmap.fr/hot/{z}/{x}/{y}.png"

        var map = L.map(document.getElementById('osm-map'));
        L.tileLayer(tileserver_humanitarian).addTo(map);

        function init_map() {
            var target = L.latLng('51.8449', '5.8428');  // Nijmegen
            map.setView(target, 12);
        }

        function place_marker(lat, lon) {
            var target = L.latLng(lat, lon);
            map.setView(target, 15);
            if (marker) {
                marker.remove();
            }
            marker = L.marker(target, { 'draggable': true, 'autoPan': true }).addTo(map);
            var name = document.getElementById('input-displayname').value
            if (name) {
                marker.bindTooltip(name, { permanent: true });
            }
            marker.addEventListener('move', (event) => {
                document.getElementById('input-lat').value = event.latlng['lat'].toFixed(7);
                document.getElementById('input-lon').value = event.latlng['lng'].toFixed(7);
            })
        }

        function debounce(func, delay) {
            let debounceTimer
            return function () {
                clearTimeout(debounceTimer)
                debounceTimer = setTimeout(() => func.apply(this, arguments), delay)
            }
        }

        var marker = null;
        var lat = document.getElementById('input-lat').value;
        var lon = document.getElementById('input-lon').value;
        if (lat != '' && lon != '') {
            place_marker(lat, lon);
        }
        else {
            init_map();
        }

        var latlon_fields = document.querySelectorAll('.update-latlon');
        const geocoding_url = "{{ url_for('geocoding') }}";
        Array.from(latlon_fields).forEach(element => {
            element.addEventListener("input", debounce((event) => {
                fetch(geocoding_url + '?' + new URLSearchParams({
                    'street': `${document.getElementById('input-street').value} ${document.getElementById('input-number').value}`,
                    'postalcode': document.getElementById('input-postal').value,
                    'city': document.getElementById('input-city').value,
                    'country': document.getElementById('input-country').value,
                }).toString())
                    .then(function (response) {
                        if (response.ok) {
                            return response.json();
                        }
                        return Promise.reject(response);
                    })
                    .then(function (json) {
                        if (json['lat'] && json['lon']) {
                            document.getElementById('input-lat').value = json['lat'];
                            document.getElementById('input-lon').value = json['lon'];
                            place_marker(json['lat'], json['lon']);
                        }
                    })
                    .catch(function (response) {
                        document.getElementById('input-lat').value = '';
                        document.getElementById('input-lon').value = '';
                        if (marker) {
                            marker.remove();
                        }
                        init_map();
                    });
            }, 1000));
        });
    })()
</script>
{% endblock %}