{% extends 'Admin/layout.html.twig' %}
{%- import 'Admin/Form/macros.html.twig' as m -%}

{% trans_default_domain 'form' %}

{% block javascripts %}
    <!-- Google Maps JavaScript API v3 key -->
    <script src="https://maps.googleapis.com/maps/api/js?key={{ google_maps_id }}"></script>
    <script>
        var bounds = new google.maps.LatLngBounds();
        var distanceMatrixService = new google.maps.DistanceMatrixService();
        var geocoder = new google.maps.Geocoder();
        var map = new google.maps.Map(document.getElementById('map-canvas'), {
            center: new google.maps.LatLng({{ ope.prof.latitude }}, {{ ope.prof.longitude }}),
            zoom: 10,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        var markers = [];
        var origins = [new google.maps.LatLng({{ ope.prof.latitude }}, {{ ope.prof.longitude }})];

        var destinationIcon = new google.maps.MarkerImage(
            '{{ asset('front/images/marker-orange.png') }}',
            new google.maps.Size(21,34),
            new google.maps.Point(0,0),
            new google.maps.Point(0,34)
        );

        var originIcon = new google.maps.MarkerImage(
            '{{ asset('front/images/marker-grey.png') }}',
            new google.maps.Size(21,34),
            new google.maps.Point(0,0),
            new google.maps.Point(0,34)
        );
        
        var chunkQty;
        var chunkSize = 20;
        var coordinates;
        var table;

        function initialize() {
            table = document.querySelector('#listusers');
        
            // Get the coordinates as objects containing latitude and longitude properties.
            // Replace these objects by Google LatLng ones.
            coordinates = JSON.parse(table.getAttribute('data-coordinates'));
            for (var i = 0; i < coordinates.length; i++) {
                coordinates[i] = new google.maps.LatLng(coordinates[i].latitude, coordinates[i].longitude);
            }
            
            chunkQty = Math.ceil(coordinates.length / chunkSize);
        }

        function calculateDistances() {
            for (var i = 0; i < chunkQty; i++) {
                window.setTimeout('calculateDistancesQuery(' + i + ')', i * 1000);
            }
        }
    
        function getChunkFromIndex(index) {
            var start = index * chunkSize;
    
            return coordinates.slice(start, start + chunkSize);
        }
    
        function calculateDistancesQuery(chunkIndex) {
            var request = {
                origins: origins,
                destinations: getChunkFromIndex(chunkIndex),
                travelMode: google.maps.TravelMode.DRIVING,
                unitSystem: google.maps.UnitSystem.METRIC,
                avoidHighways: false,
                avoidTolls: false
            };
            
            distanceMatrixService.getDistanceMatrix(request, function(response, status) {
                response.chunkIndex = chunkIndex;
    
                callback(response, status);
            });
        }
    
        function callback(response, status) {
            if (status != google.maps.DistanceMatrixStatus.OK) {
                // alert('Error was: ' + status);
                return;
            }
    
            for (var i = 0; i < origins.length; i++) {
                var results = response.rows[i].elements;
                addMarker(origins[i], false);
    
                for (var j = 0; j < results.length; j++) {
                    addMarker(coordinates[response.chunkIndex * chunkSize + j], true);
    
                    row = table.querySelector('tbody > tr:nth-child(' + (response.chunkIndex * chunkSize + j + 1) + ')');
                    
                    // On récupère les temps et distances souhaités
                    var skm = row.querySelector('.skm').getAttribute('val');
                    var stmp = row.querySelector('.stmp').getAttribute('val');
    
                    // On affiche les valeurs de google
                    row.querySelector('.km').innerHTML = results[j].distance.text;
                    row.querySelector('.tmp').innerHTML = Math.floor(results[j].duration.value/60) + ' min';
    
                    // On regarde si ça correspond
                    if (skm * 1000 > results[j].distance.value) {
                        row.querySelector('.km').style.background = '#E8A0FF';
                    }
    
                    if (stmp * 60 > results[j].duration.value) {
                        row.querySelector('.tmp').style.background = '#E8A0FF';
                    }
                }
            }
        }
    
        function addMarker(latLng, isDestination) {
            var icon = isDestination ? destinationIcon : originIcon;
    
            bounds.extend(latLng);
            map.fitBounds(bounds);
    
            markers.push(new google.maps.Marker({
                map: map,
                position: latLng,
                icon: icon
            }));
        }

        function deleteMarkers() {
            for (var i = 0; i < markers.length; i++) {
                markers[i].setMap(null);
            }
    
            markers = [];
        }

        $(function() {
            var filterUrl = $('#filters').attr('data-url');

            function changeActif()
            {
                $.ajax({
                    type: "POST",
                    url: filterUrl,
                    data: {
                        {# The Number() cast is an elegant way to retrieve a boolean value with PHP (otherwise it retrieves a string ('false' or 'true') #}
                        filterByClass: Number($('#filter-input-class').is(':checked')),
                        usePersonalLocation: Number($('#filter-input-use-personal-location').is(':checked'))
                    },
                    cache: false,
                    success: function(data) {
                        $('.listuser').html(data);
                        deleteMarkers();
                        initialize();
                    }
                });
            }

            $('.filter-input').on('change', function() {
                changeActif();
            });

            $('.fancybox').fancybox({
                autoSize: false,
                height: 500,
                width: 700,
                padding: 0,
                openEffect: 'elastic',
                closeEffect: 'elastic'
            });

            changeActif();
        });
    </script>
{% endblock %}

{% block body %}
    <header>
        <ul class="btns">
            <li class="btns-back">
                {{ m.step_back() }}
            </li>
        </ul>

        <h1>État de la demande</h1>
    </header>

    <div class="blockTop">
        <h3>Informations demande</h3>
        <p>
            <strong>Statut du demandeur&nbsp;:</strong> {{ ('word.type.user.' ~ ope.prof.type ~ '.label')|trans({}, 'word') }}<br/>
            <strong>Date du dépôt&nbsp;:</strong> {{ ope.created|date('d/m/Y') }}<br/>
            <strong>Demandeur&nbsp;:</strong> {{ ope.prof.lastname }}, {{ ope.prof.firstname }}<br/>
                {{ ope.prof.email }}<br/>
                {{ ope.prof.phone }}<br/>
            {#<strong><a href="{{ path('admin_demande_itdlc_professeur_edit', {id:ope.id}) }}#disponibilites" target="_blank" title="Modifier (dans un nouvel onglet)">Disponibilités</a>&nbsp;:</strong>#}
        </p>
        {#{% if dates|length == 0 %}#}
            {#<p>Aucune disponibilité nʼa été renseignée.</p>#}
        {#{% else %}#}
            {#<ul>#}
            {#{% for date in dates %}#}
                {#<li>#}
                    {#{% if date.dayoftheweek is not null %}#}
                        {#Tous les {{ date.dayoftheweek|lower }}#}
                    {#{% else %}#}
                        {#Le {{ date.datevisite|date('d/m/Y') }}#}
                    {#{% endif %}#}
                    {#de {{ date.startTime|date('H\\hi') }} à #}
                    {#{{ date.endTime|date('H\\hi') }}#}
                {#</li>#}
            {#{% endfor %}#}
            {#</ul>#}
        {#{% endif %}#}
    </div>

    <div class="blockTop">
        <h3>Demande</h3>
        <p><a class="btn" href="{{ path('admin_demande_itdlc_professeur_edit', {id:ope.id}) }}">
            <span>Editer la demande</span>
        </a></p>
        <p>
            <strong>Établissement&nbsp;:</strong> {{ ope.prof.establishmentName }}<br/>
            <strong>Adresse Établissement&nbsp;:</strong> {{ ope.prof.establishmentAddress }}<br/>
            <strong>CP Établissement&nbsp;:</strong> {{ ope.prof.establishmentZipcode }}<br/>
            <strong>Ville Établissement&nbsp;:</strong> {{ ope.prof.establishmentCity }}<br/>
            <strong>{{ 'form.academy.label'|trans }}&nbsp;:</strong> {{ ope.prof.academy }}<br/><br/>
            <strong>Niveau classe&nbsp;:</strong> {{ ope.classLevel }}<br/>
            <strong>Matière classe&nbsp;:</strong> {{ ope.classOption }}<br/>
            <strong>{{ 'form.itdlc.goalCategory.label'|trans }}&nbsp;:</strong> {{ ope.goalCategory|transconst('AppBundle\\Enum\\ITDLCGoalCategory') }}<br/>
            <strong>{{ 'form.itdlc.goal.label'|trans }}&nbsp;:</strong> {{ ope.goal }}<br/>
            {% for mer in ope.merITDLC %}
                {% if mer.answer is not null %}
                    <strong>{{ 'form.itdlc.date_selected.label'|trans }}&nbsp;:</strong>
                    {% if mer.answer == "date1" %}
                        {{ mer.firstDate|date('d/m/Y') }} de  {{ mer.firstDateStartTime|date('h:i') }} à  {{ mer.firstDateEndTime|date('h:i') }}
                    {% elseif mer.answer == "date2" %}
                        {{ mer.secondDate|date('d/m/Y') }} de {{ mer.secondDateStartTime|date('h:i') }} à  {{ mer.secondDateEndTime|date('h:i') }}
                    {% elseif mer.answer == "date3" %}
                        {{ mer.thirdDate|date('d/m/Y') }} de {{ mer.thirdDateStartTime|date('h:i') }} à  {{ mer.thirdDateStartTime|date('h:i') }}
                    {% else %}
                        mer.answer
                    {% endif %}
                    <br/>

                {% else %}
                    <strong>{{ 'form.itdlc.dates_proposal.label'|trans }}&nbsp;:</strong>
                    <br/>{{ mer.firstDate|date('d/m/Y') }} de {{ mer.secondDateStartTime|date('h:i') }} à  {{ mer.firstDateEndTime|date('h:i') }}
                    <br/>{{ mer.secondDate|date('d/m/Y') }} de {{ mer.firstDateStartTime|date('h:i') }} à  {{ mer.secondDateEndTime|date('h:i') }}
                    <br/>{{ mer.thirdDate|date('d/m/Y') }} de {{ mer.thirdDateStartTime|date('h:i') }} à  {{ mer.thirdDateEndTime|date('h:i') }}
                {% endif %}
            {% endfor %}
            {#
            <strong>{{ 'form.itdlc.period.label'|trans }}&nbsp;:</strong> {{ ope.period|transconst('AppBundle\\Enum\\ITDLCPeriod') }}
            #}
        </div>
    </p>
    <div class="clear"></div>
    
    <div>
        <h3>Préférence pour&nbsp;:</h3>
        {% for p in preferences %}
            {% if loop.first %}
                <ul>
            {% endif %}

            <li>{{ p.selectedUser.firstname }} {{ p.selectedUser.lastname }} ({{ p.selectedUser.establishmentCity }})</li>

            {% if loop.last %}
                </ul>
            {% endif %}
        {% endfor %}
    </div>  
  
    <div class="borderBottom"></div>

    <h3>Prendre en compte les préférences&nbsp;:</h3>
    <ul id="filters" data-url="{{ path('admin_demande_itdlc_professeur_find', {id:ope.id}) }}">
        <li class="filter" id="filter-class">
            <input class="filter-input" id="filter-input-class" type="checkbox" name="classe"/>
            <span class="checkbox"></span>
            <label for="filter-input-class">par classes</label>
        </li>
        <li class="filter" id="filter-class">
            <input class="filter-input" id="filter-input-use-personal-location" type="checkbox" name="classe"/>
            <span class="checkbox"></span>
            <label for="filter-input-use-personal-location">par résidence des intervenants</label>
        </li>
    </ul>

    <div id="inputs">
        <p><button class="btn" type="button" onclick="calculateDistances();">Lancer le matching</button></p>
        <p>Appuyer sur ce bouton pour afficher les distances et temps réels de déplacement qui correspondent aux contraintes des intervenants (en rose).</p>
        <p>Actions de couleur verte: l'ingénieur est intéressé par cette intervention</p>
    </div>
    
    <h3>Correspondance :</h3>
    <div class="listuser">
        <p>Chargement en cours...</p>
    </div>

    <div id="map-canvas"></div>
{% endblock %}