{# @var ea \EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext #}
{# @var entities \EasyCorp\Bundle\EasyAdminBundle\Collection\EntityDtoCollection #}
{# @var paginator \EasyCorp\Bundle\EasyAdminBundle\Orm\EntityPaginator #}
{% extends ea.templatePath('layout') %}

{% trans_default_domain ea.i18n.translationDomain %}

{% block body_id entities|length > 0 ? 'ea-index-' ~ entities|first.name : '' %}
{% block body_class 'index' ~ (entities|length > 0 ? ' index-' ~ entities|first.name : '') %}

{% block content_title %}
    {{ 'index'|sov_trans_admin_title(translation_entity_name) }}
{% endblock %}

{% block content_breadcrumb %}
    {{ include('@LcSov/adminlte/block/breadcrumb.html.twig') }}
{% endblock content_breadcrumb %}

{% set has_batch_actions = batch_actions|length > 0 %}
{% block page_actions %}

{% endblock page_actions %}

{% block main %}
    {% block main_prepend %}{% endblock %}
{% set _block_index_id = block('index_id') %}

<div {% if _block_index_id %}id="{% block index_id %}{% endblock index_id %}"{% endif %}>
    {# sort can be multiple; let's consider the sorting field the first one #}
    {% set sort_field_name = app.request.get('sort')|keys|first %}
    {% set sort_order = app.request.get('sort')|first %}
    {% set some_results_are_hidden = false %}
    {% set has_footer = entities|length != 0 %}
    {% set has_search = ea.crud.isSearchEnabled %}
    {% set has_filters = filters|length > 0 %}
    {% set has_datagrid_tools = has_search or has_filters %}

    {% block card_wrapper %}
        <div class="card card-table card-outline card-primary">
            {% block card_header_wrapper %}
                <div class="card-header">
                <span data-toggle="tooltip" class="badge badge-light" data-original-title="Total" title="Total">
                {{ paginator.numResults }} résultats
                </span>


                    <div class="btn-list float-sm-right">
                        <div class="global-actions">

                            {% block global_actions %}
                                {% for action in global_actions %}
                                    {{ include(action.templatePath, { action: action }, with_context = false) }}
                                {% endfor %}
                            {% endblock global_actions %}
                        </div>

                        {% block batch_actions %}
                            {% if has_batch_actions %}
                                <div class="batch-actions" style="display: none">
                                    {% for action in batch_actions %}
                                        {{ include(action.templatePath, { action: action }, with_context = false) }}
                                    {% endfor %}
                                </div>
                            {% endif %}
                        {% endblock %}
                    </div>
                </div>
            {% endblock %}
            {% block card_body_wrapper %}
                <div class="card-body">
                    <div class="">
                        <table class="table table-bordered table-hover table-striped">
                            <thead>
                            {% block table_head %}
                                <tr>
                                    {% if has_batch_actions %}
                                        <th class="">
                                            <input type="hidden" id="batch_form_entityIds" value=""/>
                                            <span><input type="checkbox"
                                                         class="form-check-input m-0 align-middle form-batch-checkbox-all"></span>
                                        </th>
                                    {% endif %}
                                    {% set ea_sort_asc = constant('EasyCorp\\Bundle\\EasyAdminBundle\\Config\\Option\\SortOrder::ASC') %}
                                    {% set ea_sort_desc = constant('EasyCorp\\Bundle\\EasyAdminBundle\\Config\\Option\\SortOrder::DESC') %}
                                    {% for field in fields ?? [] %}
                                        {% set field = field.getAsDto() %}
                                        {% if field.isDisplayedOn('index') %}

                                            {% set is_sorting_field = ea.search.isSortingField(field.property) %}
                                            {% set next_sort_direction = is_sorting_field ? (ea.search.sortDirection(field.property) == ea_sort_desc ? ea_sort_asc : ea_sort_desc) : ea_sort_desc %}
                                            {% set column_icon = is_sorting_field ? (next_sort_direction == ea_sort_desc ? 'fa-arrow-up' : 'fa-arrow-down') : 'fa-sort' %}

                                            <th class="{{ is_sorting_field ? 'sorted' }} {{ field.isVirtual ? 'field-virtual' }} {% if field.textAlign %}text-{{ field.textAlign }}{% endif %}"
                                                dir="{{ ea.i18n.textDirection }}">
                                                {% if field.isSortable %}
                                                    <a href="{{ ea_url({ page: 1, sort: { (field.property): next_sort_direction } }).includeReferrer() }}">
                                                        {% if field.label is not null %}
                                                            {{ field.label|raw }}
                                                        {% else %}
                                                            {{ field.getProperty|sov_trans_admin_field_index(translation_entity_name) }}
                                                        {% endif %}

                                                        <i class="fa fa-fw {{ column_icon }}"></i>
                                                    </a>
                                                {% else %}
                                                    {% if field.label is not null %}
                                                        <span>{{ field.label|raw }}</span>
                                                    {% else %}
                                                        <span>{{ field.getProperty|sov_trans_admin_field_index(translation_entity_name) }}</span>
                                                    {% endif %}
                                                {% endif %}
                                            </th>
                                        {% endif %}
                                    {% endfor %}

                                    <th class="w-1" {% if ea.crud.showEntityActionsAsDropdown %}width="10px"{% endif %}
                                        dir="{{ ea.i18n.textDirection }}">
                                        <span class="sr-only">{{ 'action.entity_actions'|trans(ea.i18n.translationParameters, 'EasyAdminBundle') }}</span>
                                    </th>
                                </tr>
                            {% endblock table_head %}

                            {% block table_filters %}
                                {{ include('@LcSov/adminlte/block/table_filters.html.twig') }}
                            {% endblock table_filters %}

                            </thead>

                            <tbody>
                            {% block table_body %}
                                {% for entity in entities %}
                                    {% if not entity.isAccessible %}
                                        {% set some_results_are_hidden = true %}
                                    {% else %}
                                        <tr data-id="{{ entity.primaryKeyValueAsString }}">
                                            {% if has_batch_actions %}
                                                <td><input type="checkbox" class="form-batch-checkbox"
                                                           value="{{ entity.primaryKeyValue }}"></td>
                                            {% endif %}

                                            {% for field in entity.fields %}
                                                <td class="{{ field.property == sort_field_name ? 'sorted' }} text-{{ field.textAlign }} {{ field.cssClass }}"
                                                    dir="{{ ea.i18n.textDirection }}">
{#                                                    {% if (field.property == 'id' or field.property == 'title') %}#}
{#                                                        #}{# {% if (field == 'title' or field== 'id') and (metadata.dataType=="string" or metadata.dataType=="integer") and _entity_config.name != 'ProductFamilyAdvancedEditing' %} #}
{#                                                        <a class="link-as-text"#}
{#                                                           href="{{ ea_url_short(null, 'edit', entity.instance.id) }}">#}
{#                                                            {{ include(field.templatePath, { field: field, entity: entity }, with_context = false) }}#}

{#                                                        </a>#}
{#                                                    {% else %}#}
                                                        {{ include(field.templatePath, { field: field, entity: entity }, with_context = false) }}
{#                                                    {% endif %}#}
                                                </td>
                                            {% endfor %}

                                            {% block entity_actions %}
                                                <td class="actions text-right">
                                                    {% if entity.actions.count > 0 %}
                                                        {% set has_dropdown = false %}

                                                        {% set in_dropdown_class = 'in-dropdown' %}
                                                        {% for action in entity.actions %}
                                                            {% if not (in_dropdown_class in action.cssClass) %}
                                                                {{ include(action.templatePath, { action: action, entity: entity, isIncludedInDropdown: 0 }, with_context = false) }}
                                                            {% else %}
                                                                {% set has_dropdown = true %}
                                                            {% endif %}

                                                        {% endfor %}
                                                        {% if has_dropdown %}
                                                            <div class="dropdown dropdown-actions">
                                                                <a class="dropdown-toggle btn btn-secondary btn-sm"
                                                                   href="#"
                                                                   role="button" data-toggle="dropdown"
                                                                   aria-haspopup="true"
                                                                   aria-expanded="false">
                                                                </a>

                                                                <div class="dropdown-menu dropdown-menu-right">
                                                                    {% for action in entity.actions %}
                                                                        {% if in_dropdown_class in action.cssClass %}
                                                                            {{ include(action.templatePath, { action: action, isIncludedInDropdown: 1 }, with_context = false) }}
                                                                        {% endif %}
                                                                    {% endfor %}
                                                                </div>
                                                            </div>
                                                        {% endif %}

                                                    {% endif %}

                                                    {% if not ea.crud.showEntityActionsAsDropdown %}

                                                    {% else %}

                                                    {% endif %}
                                                </td>
                                            {% endblock entity_actions %}
                                        </tr>

                                    {% endif %}
                                {% else %}
                                    <tr>
                                        <td class="no-results" colspan="100">
                                            {{ 'datagrid.no_results'|trans(ea.i18n.translationParameters, 'EasyAdminBundle') }}
                                        </td>
                                    </tr>
                                {% endfor %}

                                {% if some_results_are_hidden %}
                                    <tr class="datagrid-row-empty">
                                        <td class="text-center" colspan="{{ entities|first.fields|length + 1 }}">
                                    <span class="datagrid-row-empty-message"><i
                                                class="fa fa-lock mr-1"></i> {{ 'datagrid.hidden_results'|trans({}, 'EasyAdminBundle') }}</span>
                                        </td>
                                    </tr>
                                {% endif %}
                            {% endblock table_body %}
                            </tbody>
                        </table>

                        {% block filters_form %}
                            {% if filters_form is defined %}
                                {{ form_start(filters_form, {'attr' :{'id' : 'filters-form'}}) }}

                                {# <input type="hidden" name="entity" value="{{ _entity_config.name }}">
                        <input type="hidden" name="menuIndex" value="{{ app.request.get('menuIndex') }}">
                        <input type="hidden" name="submenuIndex" value="{{ app.request.get('submenuIndex') }}">
                        <input type="hidden" name="sortField" value="{{ app.request.get('sortField', '') }}">
                        <input type="hidden" name="sortDirection"
                               value="{{ app.request.get('sortDirection', 'DESC') }}">
                        <input type="hidden" name="action" value="{{ app.request.get('action') }}"> #}
                                {{ form_end(filters_form) }}
                            {% endif %}
                        {% endblock filters_form %}

                    </div>
                </div>
            {% endblock %}
            {% block card_footer_wrapper %}
                <div class="card-footer">
                    <div class="row">
                        {% block paginator %}
                            {{ include(ea.templatePath('crud/paginator')) }}
                        {% endblock paginator %}
                    </div>
                </div>
            {% endblock %}


            {% block delete_form %}
                {{ include('@EasyAdmin/crud/includes/_delete_form.html.twig', with_context = false) }}
            {% endblock delete_form %}

            {% if has_filters %}
                {{ include('@EasyAdmin/crud/includes/_filters_modal.html.twig') }}
            {% endif %}

            {% if has_batch_actions %}
                {{ include('@EasyAdmin/crud/includes/_batch_action_modal.html.twig', {}, with_context = false) }}
            {% endif %}
        </div>
    {% endblock card_wrapper %}

    {% block main_append %}{% endblock %}

    {% endblock main %}

    {% block body_javascript %}
        {{ parent() }}

        <script type="text/javascript">

            $(function () {

                /*   $('.action-delete').on('click', function (e) {
                       e.preventDefault();
                       const formAction = $(this).attr('formaction');

                       $('#modal-delete').modal({backdrop: true, keyboard: true})
                           .off('click', '#modal-delete-button')
                           .on('click', '#modal-delete-button', function () {
                               let deleteForm = $('#delete-form');
                               deleteForm.attr('action', formAction);
                               deleteForm.submit();
                           });
                   });*/

                /*  {% if filters|length > 0 %}
            const filterModal = document.querySelector('#modal-filters');

            const removeFilter = function (field) {
                field.closest('form').querySelectorAll('input[name^="filters[' + field.dataset.filterProperty + ']"]').forEach(hidden => {
                    hidden.remove();
                });
                field.remove();
            }

            document.querySelector('#modal-clear-button').addEventListener('click', function () {
                filterModal.querySelectorAll('.filter-field').forEach(filterField => {
                    removeFilter(filterField);
                });
                filterModal.querySelector('form').submit();
            });

            document.querySelector('#modal-apply-button').addEventListener('click', function () {
                filterModal.querySelectorAll('.filter-checkbox:not(:checked)').forEach(notAppliedFilter => {
                    removeFilter(notAppliedFilter.closest('.filter-field'));
                });
                filterModal.querySelector('form').submit();
            });

            // HTML5 specifies that a <script> tag inserted with innerHTML should not execute
            // https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Security_considerations
            // That's why we can't use just 'innerHTML'. See https://stackoverflow.com/a/47614491/2804294
            let setInnerHTML = function (element, htmlContent) {
                element.innerHTML = htmlContent;
                Array.from(element.querySelectorAll('script')).forEach(oldScript => {
                    const newScript = document.createElement('script');
                    Array.from(oldScript.attributes)
                        .forEach(attr => newScript.setAttribute(attr.name, attr.value));
                    newScript.appendChild(document.createTextNode(oldScript.innerHTML));
                    oldScript.parentNode.replaceChild(newScript, oldScript);
                });
            };

            let filterButton = document.querySelector('.action-filters-button');
            filterButton.addEventListener('click', function (event) {
                let filterModal = document.querySelector(filterButton.dataset.modal);
                let filterModalBody = filterModal.querySelector('.modal-body');

                $(filterModal).modal({backdrop: true, keyboard: true});
                filterModalBody.innerHTML = '<div class="fa-3x px-3 py-3 text-muted text-center"><i class="fas fa-circle-notch fa-spin"></i></div>';

                $.get(filterButton.getAttribute('href'), function (response) {
                    setInnerHTML(filterModalBody, response);
                });

                event.preventDefault();
                event.stopPropagation();
            });
            filterButton.setAttribute('href', filterButton.getAttribute('data-href'));
            filterButton.removeAttribute('data-href');
            filterButton.classList.remove('disabled');
            {% endif %}


            {% if has_batch_actions %}

            {% endif %}*/
            });
        </script>

        {% if app.request.get('query') is not empty %}
        <script type="text/javascript">
            const search_query = "{{ ea.search.query|default('')|e('js') }}";
            // the original query is prepended to allow matching exact phrases in addition to single words
            $('#main').find('table tbody td:not(.actions)').highlight($.merge([search_query], search_query.split(' ')));
        </script>
        {% endif %}
    {% endblock %}
