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

{% block javascripts %}
    <!-- Google Maps JavaScript API v3 key -->
    <script src="https://maps.googleapis.com/maps/api/js?key={{ google_maps_id }}"></script>
    <script>
        //<![CDATA[
        $(function() {
            var geocoder = new google.maps.Geocoder();
            var fieldPrefix = '#operation_pee_';

            function isZipcodeFR(x) {
                return /^([0-9]{5})$/.test(x);
            }
    
            function getCountryByZipcode(x) {
                
                var country;
    
                switch (x.substr(0, 3)) {
                    case "971" : 
                                country = "Guadeloupe"; break; 	
                    case "973" : 
                                country = "Guyane"; break; 	
                    case "975" : 
                                country = "St-Pierre-et-Miquelon"; break;
                    case "972" : 
                                country = "Martinique"; break; 	
                    case "974" : 
                                country = "La Réunion"; break; 	
                    case "976" : 
                                country = "Mayotte"; break;
                    case "984" : 
                                country = "Terres-Australes et Antarctiques"; break; 	
                    case "987" : 
                                country = "Polynésie Française"; break;
                    case "986" : 
                                country = "Wallis-et-Futuna"; break; 	
                    case "988" : 
                                country = "Nouvelle-Calédonie"; break;
                    default :
                                country = "France"; break;
                }
                
                return country;
            }

            /**
            * Build an addresse from form fields.
            * Field's name are deduced from the given properties.
            */
            function buildAddress(properties) {
                var address = [];
                var country = '';

                for (var i = 0; i < properties.length; i++) {
                    address.push($(fieldPrefix + properties[i]).val());

                    if (isZipcodeFR($(fieldPrefix + properties[i]).val())) {
                        country = getCountryByZipcode($(fieldPrefix + properties[i]).val());
                    }
                }

                if (country !== '') {
                    address.push(country);
                }

                return address;
            }

            /**
            * Geocode an address, and update the form fields if the geocoding was successful
            */
            function geocode(address, latPropertyName, lngPropertyName) {
                var lat, lng;

                geocoder.geocode({'address': address.join(' ')}, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        lat = results[0].geometry.location.lat();
                        lng = results[0].geometry.location.lng();

                        // Update hidden fields with coordinates found
                        $(fieldPrefix + latPropertyName).val(lat);
                        $(fieldPrefix + lngPropertyName).val(lng);
                    }
                });
            }

            /**
            * Initialize the address geocoding:
            * 1. React on the 'blur' form event of the fields
            * 2. Validate the adress
            * 3. Geocode the address
            * 4. Fill the appropriate fields with the coordinates
            */
            function initAddressGeocoding(properties, latPropertyName, lngPropertyName) {
                // Build form field names from the property names
                var fields = properties.map(function(property) {
                    return fieldPrefix + property;
                });

                // 1. React on the 'change' (legacy of blur : cause limit API quota) form event of the fields
                $(fields.join(',')).on('change', function() {
                    var address = buildAddress(properties);

                    // 2. Validate the adress: every part of the address must be at least 1 character long
                    var triggerGeocoding = address.every(function(adr) { return adr.length > 0});

                    if (triggerGeocoding) {
                        // 3. Geocode the address
                        // 4. Fill the appropriate fields with the coordinates
                        geocode(address, latPropertyName, lngPropertyName);
                    };
                });
            }

            initAddressGeocoding(
                ['address', 'zipCode', 'city'],
                'latitude',
                'longitude'
            );
        });
        //]]>
    </script>
{% endblock javascripts %}

{% block body %}
    <header>
        <ul class="btns">
            <li class="btns-back">
                {{ m.step_back() }}
            </li>
            <li>
                <button class="btn btn-save" form="form-operationpeeadd">
                    {{ 'action.save'|trans({}, 'action') }}
                </button>
            </li>
        </ul>

        <h1>Ajouter une opération PEE</h1>
    </header>

    {{ form_start(form, {'attr':{'id':'form-operationpeeadd'}}) }}

        <div class="left">
            <h2>Inscription</h2>
            {{ form_row(form.state) }}
            {{ form_row(form.nbPeople) }}
            {{ form_row(form.publish) }}
            {{ form_row(form.unpublish) }}
            {{ form_row(form.is_identity_mandatory) }}
            {{ form_row(form.urlExternalRegistration) }}

            <h2>Date</h2>
            {{ form_row(form.dateVisite) }}
            {{ form_row(form.startTime) }}
            {{ form_row(form.endTime) }}

            <h2>Description</h2>
            {{ form_row(form.title) }}
            {{ form_row(form.presentation) }}
            {{ form_row(form.visit) }}
            {{ form_row(form.category) }}
        </div>

        <div class="right">
            <h2>Lieu</h2>
            {{ form_row(form.new) }}
            {{ form_row(form.company) }}
            {{ form_row(form.site) }}
            {{ form_row(form.address) }}
            {{ form_row(form.zipCode) }}
            {{ form_row(form.city) }}
            {{ form_row(form.latitude) }}
            {{ form_row(form.longitude) }}
            {{ form_row(form.academy) }}
            {{ form_row(form.siteImage1File) }}
            {{ form_row(form.siteImage2File) }}
            {{ form_row(form.siteImage3File) }}
        </div>

        <div class="clear"></div>

        <div class="left">
            <h2>Verbatim</h2>
            {{ form_row(form.quoteContent) }}
            {{ form_row(form.quoteAuthor) }}
            {{ form_row(form.quoteAuthorJob) }}
            {{ form_row(form.category) }}
        </div>

        <div class="right">
            <h2>Informations additionelles</h2>
            {{ form_row(form.namely) }}
            {{ form_row(form.audience) }}
            {{ form_row(form.partner) }}
            {{ form_row(form.note) }}
        </div>

        <div class="clear"></div>
    {{ form_end(form) }}

    <ul class="btns">
        <li>
            <button class="btn btn-save" form="form-operationpeeadd">
                {{ 'action.save'|trans({}, 'action') }}
            </button>
        </li>
    </ul>
{% endblock %}
