{% macro select2_extrahead() %}

    <link rel="stylesheet" href="{{ asset('css/select2.min.css') }}">
    <link rel="stylesheet" href="{{ asset('css/select2-bootstrap-5-theme.min.css') }}">
    <script src="{{ asset('js/select2.min.js') }}"></script>
    <script>
        $(function () {
            $.fn.select2.defaults.set("theme", "bootstrap-5");

            $('select[multiple]').select2();
        });
    </script>
{% endmacro %}

{% macro toggle_extrahead() %}

    <link rel="stylesheet" href="{{ asset('css/bootstrap-toggle.min.css') }}">
    <script src="{{ asset('js/bootstrap-toggle.min.js') }}"></script>
{% endmacro %}

{% macro toggle_autosubmit_extrafooter() %}
    <script>
        $(function() {
            $('[data-toggle]').on('change', function() {
                var $form = $(this).closest('form');
                // We use a timeout of 300 ms here since the animation looks super
                // ugly if we do not do this.
                setTimeout(function() {
                    $form.submit();
                }, 300);
            });
        });
    </script>
{% endmacro %}

{% macro coloris_extrahead() %}
    <link rel="stylesheet" href="{{ asset('css/coloris.min.css') }}">
    <script src="{{ asset('js/coloris.min.js') }}"></script>

    <script>
        function bindColor() {
            Coloris({
                el: '[data-color-picker]',
                clearButton: {
                    show: true
                }
            });
        }

        $(function() {
            bindColor();
        });
    </script>
{% endmacro %}

{% macro table_extrahead() %}

    <link rel="stylesheet" href="{{ asset('css/dataTables.bootstrap5.min.css') }}">
    <script src="{{ asset('js/dataTables.min.js') }}"></script>
    <script src="{{ asset('js/dataTables.bootstrap5.min.js') }}"></script>
    <style>
        .data-table td a:not(.showlink), .data-table td a:hover:not(.showlink) {
            text-decoration: none;
            color: inherit;
        }

        .data-table th {
            white-space: nowrap;
        }

        .data-table td {
            white-space: nowrap;
            padding-top: 1px;
            padding-bottom: 1px;
        }

        .dataTables_filter {
            text-align: inherit;
        }

        .table-wrapper {
            display: inline-block;
        }
    </style>
{% endmacro %}

{% macro table(data, fields, options) %}
    {%- set table_id = options.id|default('table-' ~ random()) %}
    <div class="table-wrapper">
        <table id="{{ table_id }}" style="width:auto" class="data-table table table-sm table-striped
                {% if options.full_clickable is defined and options.full_clickable %}table-full-clickable-cell{% endif %}">
            <thead class="">
            <tr>
                {%- set num_actions = data | numTableActions %}
                {%- if options.grouped|default(false) %}
                    <th scope="col" class="group-toggle-column"></th>
                {%- endif %}
                {%- set default_sort = 0 %}
                {%- set default_sort_order = 'asc' %}
                {%- for key,column in fields %}
                    {%- if column.default_sort|default(false) %}
                        {%- set default_sort = loop.index0 + (options.grouped|default(false) ? 1 : 0) %}
                        {%- if column.default_sort_order is defined %}
                            {%- set default_sort_order = column.default_sort_order %}
                        {%- endif %}
                    {%- endif %}

                    <th scope="col" class="
                        {%- if column.sort is defined and column.sort %}sortable{%- endif %}
                        {%- if (column.search is not defined) or column.search %} searchable{%- endif %}">
                        {%- if column.raw|default(false) %}{{- column.title|raw -}}{% else %}{{- column.title|nl2br -}}{% endif -%}
                    </th>
                {%- endfor %}
                {%- if num_actions > 0 %}
                    {%- for i in 1..num_actions %}

                        <th scope="col"></th>
                    {%- endfor %}
                {%- endif %}

            </tr>
            </thead>
            <tbody>
            {%- for row in data %}
                {{ _self.table_row(row, fields, num_actions, options) }}
            {%- endfor %}
            </tbody>
        </table>
    </div>
    <script>
        $().ready(function () {
            $('#{{ table_id }}').DataTable({
                "paging": false,
                "retrieve": true,
                "searching": {{ options.searching | default('true') }},
                "ordering": {{ options.ordering | default('true') }},
                "order": [[ {{ default_sort }}, '{{ default_sort_order }}']],
                "info": false,
                "autoWidth": true,
                "language": {
                    "searchPlaceholder": "filter table",
                    "search": "_INPUT_",
                },
                "aoColumnDefs": [
                    { "aTargets": ["sortable"], "bSortable": true },
                    { "aTargets": ["searchable"], "bSearchable": true },
                    { "aTargets": ["_all"], "bSortable": false, "bSearchable": false }
                ],
            });
        });
    </script>
{% endmacro %}

{% macro table_row(row, fields, num_actions, options, is_child = false, parent_expanded = true) %}
    <tr class="{{ row.cssclass|default('') }}{% if is_child %} table-row-child table-light{% endif %}{% if row.children|default([]) is not empty %} table-row-parent{% endif %}{% if is_child and not parent_expanded %} d-none{% endif %}"
            {%- if row.style is defined %} style="{{ row.style }}"{% endif %}
            {%- if row.id is defined %} data-row-id="{{ row.id }}"{% endif %}
            {%- if is_child and row.parent_id is defined %} data-row-parent-id="{{ row.parent_id }}"{% endif %}>
        {%- if options.grouped|default(false) %}
            <td class="group-toggle-cell">
                {%- if row.children|default([]) is not empty %}
                    <span class="group-toggle" data-group-toggle="{{ row.id }}">
                        <i class="fas fa-chevron-{{ row.expanded|default(false) ? 'down' : 'right' }} group-chevron" id="chevron-{{ row.id }}"></i>
                    </span>
                {%- endif %}
            </td>
        {%- endif %}
        {%- for key,column in fields %}
            {%- set item = attribute(row.data, key) %}

            <td
                    class="{{ item.cssclass|default('') }}{% if key == "status" and 'disabled' not in row.cssclass %} {{ item.value|statusClass() }}{% endif %}"
                    {%- if item.title is defined %} title="{{ item.title }}"{% endif %}
                    {%- if item.filterKey is defined and item.filterValue is defined %} data-{{ item.filterKey }}="{{ item.filterValue }}"{% endif %}
                    {%- if item.sortvalue is defined %} data-sort="{{ item.sortvalue }}"{% endif %}
                    {% if (column.render | default('')) == "entity_id_badge" %}style="text-align: right;" {% endif %}>
                {%- if item.link is defined %}
                    {%- if item.link %}<a href="{{ item.link }}" {%- if item.showlink is defined %} class="showlink"{% endif %}>{% endif %}
                {%- elseif row.link is defined and not item.toggle_partial is defined %}<a href="{{ row.link }}">{% endif %}
                {% if item.toggle_partial is defined %}
                    {% include 'jury/partials/' ~ item.toggle_partial with item.partial_arguments %}
                    {% if item.suffix is defined and item.suffix %} {{ item.suffix }}{% endif %}
                {% elseif key == "status" %}
                    {{- (item.value|default(item.default|default('')))|statusIcon -}}
                {% elseif key == "country" %}
                    {{- (item.value|default(item.default|default('')))|countryFlag -}}
                {% elseif key == "affiliation_logo" %}
                    {{- (item.value|default(item.default|default('')))|affiliationLogo(item.title) -}}
                {% elseif key == "warning_content" %}
                    {{- item.value|printWarningContent -}}
                {% elseif key == "badges" %}
                    {% for badge in item.value %}
                        {{- badge|problemBadge }}
                    {% endfor %}
                {% elseif (column.render | default('')) == "entity_id_badge" %}
                    {% if item.value %}{{- item.value|entityIdBadge -}}{% endif %}
                {% else %}
                    {%- if column.raw|default(false) %}{{- (item.value|default(item.default|default('')))|raw -}}{% else %}{{- (item.value|default(item.default|default(''))) -}}{% endif -%}
                {% endif %}
                {% if item.icon is defined %}<i class="fas fa-{{ item.icon }}"></i>{%- endif %}
                {%- if item.link is defined %}
                    {% if item.link %}
                        </a>
                    {% endif %}
                {% else %}
                    {% if row.link is defined and not item.toggle_partial is defined %}
                        </a>
                    {% endif %}
                {% endif %}
            </td>
        {%- endfor %}
        {%- for action in row.actions %}

            <td>
                {%- if action %}

                    <a {% if action.disabled is defined and action.disabled %}class="disabled"{% endif %} {% if action.link is defined %}href="{{ action.link }}"{% endif %} title="{{ action.title }}" {% if action.ajaxModal is defined and action.ajaxModal %}data-ajax-modal{% endif %}>
                        <i class="fas fa-{{ action.icon }}"></i>
                    </a>
                {%- endif %}

            </td>
        {%- endfor %}

    </tr>
    {%- if row.children|default([]) is not empty %}
        {%- for child in row.children %}
            {{ _self.table_row(child, fields, num_actions, options, true, row.expanded|default(false)) }}
        {%- endfor %}
    {%- endif %}
{% endmacro %}

{% macro collection_scripts() %}
    <script>
        var $collectionHolder;

        $(function () {
            $collectionHolder = $('[data-collection-holder]');
            $collectionHolder.data('index', $collectionHolder.find('tr').length);
            $('[data-add]').on('click', function () {
                addCollectionItem($collectionHolder);
            });

            $('[data-delete]').on('click', function () {
                $(this).closest('tr').remove();
            });

            function addCollectionItem($collectionHolder) {
                var prototype = $('[data-prototype]').text();
                var index = $collectionHolder.data('index');
                prototype = prototype.replace(/__name__/g, index);
                $collectionHolder.data('index', index + 1);
                var $prototype = $(prototype);
                $prototype.find('[data-delete]').on('click', function () {
                    $(this).closest('tr').remove();
                });

                $collectionHolder.append($prototype);

                if ($collectionHolder.data('after-add')) {
                    window[$collectionHolder.data('after-add')]();
                }
            }
        });
    </script>
{% endmacro %}

{% macro progress_bar(message = '') %}
    <div class="alert alert-info">
        {% if message is not empty %}
            <p>{{ message }}</p>
        {% endif %}
        <div class="progress mt-2 mb-2">
            <div id="progress-bar-progress"
                 class="progress-bar progress-bar-animated progress-bar-striped" style="width: 0;">
                0%
            </div>
        </div>
        <div id="progress-bar-log"></div>
        <div class="mt-4" id="progress-bar-message"></div>
    </div>
{% endmacro %}

{% macro progress_loader(url, data = null) %}
    <script>
        $(function () {
            var $progress = $('#progress-bar-progress');
            var $log = $('#progress-bar-log');
            var $message = $('#progress-bar-message');

            var currentData = '';

            var consume = function(responseReader) {
                return responseReader.read().then(function(result) {
                    if (result.done) { return; }

                    var chunk = new TextDecoder().decode(result.value);
                    currentData += chunk;

                    if (currentData[currentData.length - 1] === "}") {
                        // Make sure we start at the last {
                        var data = JSON.parse(currentData.substring(currentData.lastIndexOf('{')));
                        currentData = '';

                        $progress
                            .attr('style', 'width: ' + data.progress + '%;')
                            .text(data.progress + '%');

                        if (data.progress == '100') {
                            $progress
                                .removeClass('progress-bar-animated')
                                .removeClass('progress-bar-striped')
                                .addClass('bg-success');
                        }

                        if (data.message) {
                            $message.html(data.message);
                            return;
                        }

                        if (data.redirect) {
                            window.location.replace(data.redirect);
                            return;
                        }

                        $log.html(data.log);
                    }

                    return consume(responseReader);
                });
            };
            fetch('{{ url }}', {
                method: 'POST',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    {% if data %}'Content-Type': 'application/x-www-form-urlencoded',{% endif %}
                },
                {% if data %}body: '{{ data | raw }}',{% endif %}
            }).then(function(response) {
                return consume(response.body.getReader());
            });
        });
    </script>
{% endmacro %}
