{% 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({{ engineer.latitude }}, {{ engineer.longitude }}),
            zoom: 10,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        var markers = [];
        var origins = [new google.maps.LatLng({{ engineer.latitude }}, {{ engineer.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') #}
                        filterByEstablishment: Number($('#filter-input-establishment').is(':checked')),
                        filterByClass: Number($('#filter-input-class').is(':checked'))
                    },
                    cache: false,
                    success: function(data) {
                        $('.listuser').html(data);
                        deleteMarkers();
                        initialize();
                    }
                });
            }

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

            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>
        <b>Statut du demandeur :</b> {{ ('word.type.user.' ~ engineer.type ~ '.label')|trans({}, 'word') }}<br/>
        <b>Demandeur :</b> {{ engineer.lastname }}, {{ engineer.firstname }}<br/>
                    {{ engineer.email }}<br/>
                    {{ engineer.phone }}<br/><br/>
        <b>Distance de déplacement souhaitée :</b> {{ engineer.transportKm }} km<br/>
        <b>Temps de déplacement souhaité :</b> {{ engineer.transportTime }} min<br/>
    </div>
    <div class="blockTop">
        <h3>Demandeur</h3>
       
        <p>
        <b>Entreprise :</b> {{ engineer.establishmentName }}<br/>
        <b>Adresse Entreprise :</b> {{ engineer.establishmentAddress }}<br/>
        <b>CP Entreprise :</b> {{ engineer.establishmentZipcode }}<br/>
        <b>Ville Entreprise :</b> {{ engineer.establishmentCity }}<br/>
        <b>Niveau classe :</b> {{ engineer.classroom|join(' / ') }}<br/>
        <b>Objectif :</b> {{ engineer.briefing }}
        </p>
    </div>
    <div class="clear"></div>
    <div>
        <h3>Préférence pour :</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_ingenieur_find', {id:engineer.id}) }}">
        <li class="filter" id="filter-establishment">
            <input class="filter-input" id="filter-input-establishment" type="checkbox" name="etablissement"/>
            <span class="checkbox"></span>
            <label for="filter-input-establishment">par établissement</label>
        </li>
        <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>
    </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 enseignants (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 %}