{#

This file is part of the Sonata package.

(c) Thomas Rabaix <thomas.rabaix@sonata-project.org>

For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.

#}
{% apply spaceless %}
    <select id="{{ id }}_autocomplete_input" data-sonata-select2="false"
        {%- if read_only|default(false) %} readonly="readonly"{% endif -%}
        {%- if disabled %} disabled="disabled"{% endif %}
        {%- if multiple %} multiple="multiple"{% endif %}
    >
        {%- for idx, val in value|filter((val, idx) => idx~'' != '_labels') -%}
            <option value="{{ val }}" selected>{{ value['_labels'][idx] }}</option>
        {%- endfor -%}
    </select>

    <div id="{{ id }}_hidden_inputs_wrap">
        {% if multiple -%}
            {%- for idx, val in value|filter((val, idx) => idx~'' != '_labels') -%}
                <input type="hidden" name="{{ full_name }}[]" {%- if disabled %} disabled="disabled"{% endif %} value="{{ val }}">
            {%- endfor -%}
        {% else -%}
            <input type="hidden" name="{{ full_name }}" {%- if disabled %} disabled="disabled"{% endif %} value="{{ value[0]|default('') }}">
        {% endif -%}
    </div>

    {% if sonata_admin.field_description and sonata_admin.field_description.hasAssociationAdmin %}
        <div id="field_actions_{{ id }}" class="field-actions">
            {% set display_btn_add = sonata_admin.edit != 'admin' and sonata_admin.field_description.associationadmin.hasRoute('create')
                                     and sonata_admin.field_description.associationadmin.isGranted('CREATE') and btn_add %}
            {% if display_btn_add %}
                <a  href="{{ sonata_admin.field_description.associationadmin.generateUrl('create',
                             sonata_admin.field_description.getOption('link_parameters', {}))
                          }}"
                    onclick="return start_field_dialog_form_add_{{ id }}(this);"
                    class="btn btn-success btn-sm sonata-ba-action"
                    {# NEXT_MAJOR: Remove the fallback on null and on btn_catalogue #}
                    title="{{
                        btn_translation_domain|default(null) is same as(false)
                        ? btn_add
                        : btn_add|trans({}, btn_translation_domain|default(btn_catalogue))
                    }}"
                    >
                    <i class="fas fa-plus-circle"></i>
                    {# NEXT_MAJOR: Remove the fallback on null and on btn_catalogue #}
                    {{
                        btn_translation_domain|default(null) is same as(false)
                        ? btn_add
                        : btn_add|trans({}, btn_translation_domain|default(btn_catalogue))
                    }}
                </a>
                {% include '@SonataAdmin/CRUD/Association/edit_modal.html.twig' %}
                {% include '@SonataAdmin/CRUD/Association/edit_many_script.html.twig' %}
            {% endif %}
        </div>
    {% endif %}

    <script>
        {% autoescape 'js' %}
        jQuery(function ($) {
            var autocompleteInput = $('#{{ id }}_autocomplete_input');

            var select2Options = {
                {%- set allowClearPlaceholder = (not multiple and not required) ? ' ' : '' -%}
                placeholder: '{{ placeholder ?: allowClearPlaceholder }}', // allowClear needs placeholder to work properly
                allowClear: {{ required ? 'false' : 'true' }},
                enable: {{ disabled ? 'false' : 'true' }},
                readonly: {{ attr.read_only|default(false) ? 'true' : 'false' }},
                minimumInputLength: {{ minimum_input_length }},
                theme: 'bootstrap',
                width: function() {
                    return Admin.get_select2_width(jQuery(this));
                },
                language: "{{ canonicalize_locale_for_select2() }}",
                dropdownAutoWidth: {{ dropdown_auto_width ? 'true' : 'false' }},
                containerCssClass: '{{ container_css_class ~ ' form-control' }}',
                dropdownCssClass: '{{ dropdown_css_class }}',
                dropdownParent: autocompleteInput.parents('.modal').length > 0 ? autocompleteInput.parents('.modal') : $(document.body),
                ajax: {
                    url:  '{{ url ?: path(route.name, route.parameters|default([])) }}',
                    dataType: 'json',
                    delay: {{ delay == 100 and quiet_millis != 100 ? quiet_millis : delay }}, // NEXT_MAJOR: Replace by `{{ delay }}` instead.
                    cache: {{ cache ? 'true' : 'false' }},
                    processResults: function (data, params) {
                        return {
                            results: data.items,
                            pagination: {
                                more: data.more
                            }
                        };
                    },
                    data: function (params) {
                        {% block sonata_type_model_autocomplete_ajax_request_parameters %}
                        return {
                                //search term
                                '{{ req_param_name_search }}': params.term,

                                // page size
                                '{{ req_param_name_items_per_page }}': {{ items_per_page }},

                                // page number
                                '{{ req_param_name_page_number }}': (params.page !== 'undefined' ? params.page : 1),

                                // admin
                                {% if sonata_admin.admin %}
                                    'uniqid': '{{ sonata_admin.admin.uniqid }}',
                                    '_sonata_admin': '{{ sonata_admin.admin.baseCodeRoute|e('js') }}',
                                {% elseif admin_code %}
                                    '_sonata_admin': '{{ admin_code|e('js') }}',
                                {% endif %}

                                {% if context == 'filter' %}
                                    'field':  '{{ full_name|replace({'filter[': '', '][value]': '', '__':'.'}) }}',
                                    '_context': 'filter'
                                {% else %}
                                    'field':  '{{ name }}'
                                {% endif %}

                                // other parameters
                                {% if req_params is not empty %},
                                    {%- for key, value in req_params -%}
                                        '{{- key -}}': '{{- value -}}'
                                        {%- if not loop.last -%}, {% endif -%}
                                    {%- endfor -%}
                                {% endif %}
                        };
                        {% endblock %}
                    },
                },
                escapeMarkup: function (m) { return m; }, // we do not want to escape markup since we are displaying html in results
                templateResult: function (item) {
                    // When selecting a new result, the label is undefined and the correct property is text
                    if (typeof item.label === 'undefined') {
                        item.label = item.text;
                    }

                    return {% block sonata_type_model_autocomplete_dropdown_item_format -%}
                        {% if safe_label|default(false) %}
                            '<div class="{{ dropdown_item_css_class }}">'+item.label+'<\/div>'
                        {% else %}
                            jQuery('<div class="{{ dropdown_item_css_class }}">').text(item.label).prop('outerHTML')
                        {% endif %}
                    {%- endblock %}; // format of one dropdown item
                },
                templateSelection: function (item) {
                    // The searching... placeholder appears as text
                    if (typeof item.label === 'undefined') {
                        item.label = item.text;
                    }

                    return {% block sonata_type_model_autocomplete_selection_format -%}
                        {% if safe_label|default(false) %}
                            item.label
                        {% else %}
                            jQuery('<div>').text(item.label).prop('innerHTML')
                        {% endif %}
                    {%- endblock %}; // format selected item '<b>'+item.label+'</b>';
                },
            };

            autocompleteInput.select2(select2Options);

            autocompleteInput.on('select2:select select2:unselect', function(e) {
                if (e.type === 'select2:select') {
                    e.added = e.params.data;
                }
                if (e.type === 'select2:unselect') {
                    e.removed = e.params.data;
                }

                // console.log('change '+JSON.stringify({val:e.val, added:e.added, removed:e.removed}));

                // remove input
                if (undefined !== e.removed && null !== e.removed) {
                    var removedItems = e.removed;

                    {% if multiple %}
                        if(!$.isArray(removedItems)) {
                            removedItems = [removedItems];
                        }

                        var length = removedItems.length;
                        for (var i = 0; i < length; i++) {
                            el = removedItems[i];
                            $('#{{ id }}_hidden_inputs_wrap input:hidden[value="'+el.id+'"]').remove();
                        }
                    {%- else -%}
                        $('#{{ id }}_hidden_inputs_wrap input:hidden').val('');
                    {%- endif %}
                }

                // add new input
                var el = null;
                if (undefined !== e.added) {

                    var addedItems = e.added;

                    {% if multiple %}
                        if(!$.isArray(addedItems)) {
                            addedItems = [addedItems];
                        }

                        var length = addedItems.length;
                        for (var i = 0; i < length; i++) {
                            el = addedItems[i];
                            $('#{{ id }}_hidden_inputs_wrap').append('<input type="hidden" name="{{ full_name }}[]" value="'+el.id+'" />');
                        }
                    {%- else -%}
                        $('#{{ id }}_hidden_inputs_wrap input:hidden').val(addedItems.id);
                    {%- endif %}
                }
            });

            // remove unneeded autocomplete text input before form submit
            autocompleteInput.closest('form').submit(function()
            {
                autocompleteInput.remove();
                return true;
            });

            // Automatically select the created record after closing the popup window
            {% if sonata_admin.field_description
                and sonata_admin.field_description.hasAssociationAdmin
                and btn_add
                and sonata_admin.field_description.associationadmin.hasRoute('create')
                and sonata_admin.field_description.associationadmin.hasAccess('create') %}

                {% set create_url = sonata_admin.field_description.associationadmin.generateUrl('create', sonata_admin.field_description.getOption('link_parameters', {})) %}

                $(document).ajaxSuccess(function(event, xhr, settings) {
                  if(typeof xhr.responseJSON != 'undefined') {
                      if ('{{ create_url }}'.indexOf(settings.url) !== -1 && typeof xhr.responseJSON != 'string' && xhr.responseJSON.result == 'ok') {
                        var item = new Option(
                          new DOMParser().parseFromString(xhr.responseJSON.objectName, "text/html").documentElement.textContent,
                          xhr.responseJSON.objectId,
                          true, true
                          );

                        // append to Select2
                        autocompleteInput.append(item).trigger('change');

                        // manually trigger the `select2:select` event
                        autocompleteInput.trigger({
                            type: 'select2:select',
                            params: {
                                data: autocompleteInput.select2('data')
                            }
                        });

                        {% if multiple %}
                          $('#{{ id }}_hidden_inputs_wrap').append('<input type="hidden" name="{{ full_name }}[]" value="'+xhr.responseJSON.objectId+'" />');
                        {% else %}
                          $('#{{ id }}_hidden_inputs_wrap').html('<input type="hidden" name="{{ full_name }}" value="'+xhr.responseJSON.objectId+'" />');
                        {% endif %}
                      }
                  }
                });
            {% endif %}
        });
        {% endautoescape %}
    </script>
{% endapply %}
