{% load static i18n %}
{{ select }}

<link rel="stylesheet" type="text/css" href="{% static "cms_qe/css/table/columns-widget.css" %}">

<div>
    <p>
        {% trans 'Drag & drop certain columns to "Selected columns" list to show them on the page. You can also change columns order.' %}
    </p>

    <div class="cms-qe-table-columns">

        <div class="field-box">
            <label class="required">{% trans "Unselected columns" %}:</label>
            <ul id="{{ id }}_unselected_columns" class="actions-list cms-qe-table-column"></ul>
        </div>

        <div class="field-box">
            <label class="required">{% trans "Selected columns" %}:</label>
            <ul id="{{ id }}_selected_columns" class="actions-list cms-qe-table-column"></ul>
        </div>

    </div>
</div>
<script src="{% static "cms_qe/js/table/Sortable.min.js" %}"></script>

<script>

    // Support for table_widget.html.
    window.cmsQeColumnsValue = {% if value %}{{ value|safe }}{% else %}[]{% endif %};
    var columnsSelect = window.cmsQeColumnsSelect = {{ id }};
    var allColumnsUl = document.getElementById('{{ id }}_unselected_columns');
    var selectedColumnsUl = document.getElementById('{{ id }}_selected_columns');

    function getOptionByValue(value) {
        return document.querySelector('select#' + columnsSelect.id + ' > option[value="' + value + '"]');
    }

    var unselectedColumnsSortable = new Sortable(allColumnsUl, {
        group: "cms_qe_table_columns",
        sort: false,
        onAdd: function (evt) {
            var opt = getOptionByValue(evt.item.getAttribute("data-id"));
            opt.selected = false;
            // Unselected Option is removed and append at the end for better using in sorting of selected options.
            // Otherwise, then there will be problems with inserting option on a specific index
            // because the unselected options will be mixed with the selected ones
            // (see functions onAdd and onUpdate in selectedColumnsSortable below)
            columnsSelect.removeChild(opt);
            columnsSelect.appendChild(opt);
            window.sortList(allColumnsUl);
        }
    });

    function updateSelectedLi(evt) {
        var opt = getOptionByValue(evt.item.getAttribute("data-id"));
        columnsSelect.removeChild(opt);
        opt.selected = true;
        columnsSelect.insertBefore(opt, columnsSelect.children[evt.newIndex]);
    }

    var selectedColumnsSortable = new Sortable(selectedColumnsUl, {
        group: "cms_qe_table_columns",
        onAdd: updateSelectedLi,
        onUpdate: updateSelectedLi
    });


</script>
