

$(document).ready(function() {
    lcCrudIndexToggle() ;
    lcCrudIndexBatchActions() ;
    lcCrudIndexInitFilter();
}) ;

function lcCrudIndexToggle() {
    const toggles = document.querySelectorAll('.custom-switch input[type="checkbox"]');
    for (i = 0; i < toggles.length; i++) {
        toggles[i].addEventListener('change', function () {
            const toggle = this;
            const newValue = this.checked;
            const oldValue = !newValue;
            const toggleUrl = this.closest('.custom-switch').dataset.url + "&newValue=" + newValue.toString();

            let toggleRequest = $.ajax({type: "POST", url: toggleUrl, data: {}, dataType: 'json'});

            toggleRequest.done(function (response) {
                SovNotification.add('success', 'La propriété a bien été mise à jour.');
            });

            toggleRequest.fail(function () {
                toggle.checked = oldValue;
                toggle.disabled = true;
                toggle.closest('.checkbox-switch').classList.add('disabled');
                SovNotification.add('error', 'Une erreur est survenue.');
            });
        });
    }
}

function lcCrudIndexBatchActions() {
    const titleContent = $('.content-header-title > .title').html();
    $(document).on('click', '.deselect-batch-button', function () {
        $(this).closest('.content').find(':checkbox.form-batch-checkbox-all').prop('checked', false).trigger('change');
    });
    $(document).on('change', '.form-batch-checkbox-all', function () {
        $(this).closest('.content').find(':checkbox.form-batch-checkbox').prop('checked', $(this).prop('checked')).trigger('change');
    });
    $(document).on('change', '.form-batch-checkbox', function () {
        const $content = $(this).closest('.content-wrapper');
        let $input = $content.find(':hidden#batch_form_entityIds');
        let ids = $input.val() ? $input.val().split(',') : [];
        const id = $(this).val();

        if ($(this).prop('checked')) {
            $(this).closest('tr').addClass('selected-row');
            if (-1 === ids.indexOf(id)) {
                ids.push(id);
            }
        } else {
            $(this).closest('tr').removeClass('selected-row');
            ids = ids.filter(function (value) {
                return value !== id
            });
            $content.find(':checkbox.form-batch-checkbox-all').prop('checked', false);
        }

        if (0 === ids.length) {
            $content.find('.global-actions').show();
            $content.find('.batch-actions').hide();
            $content.find('table').removeClass('table-batch');
        } else {
            $content.find('.batch-actions').show();
            $content.find('.global-actions').hide();
            $content.find('table').addClass('table-batch');
        }

        $input.val(ids.join(','));
        $content.find('.content-header-title > .title').html(0 === ids.length ? titleContent : '');
    });

    let modalTitle = $('#batch-action-confirmation-title');
    const titleContentWithPlaceholders = modalTitle.text();

    $('[data-action-batch]').on('click', function (event) {
        event.preventDefault();
        event.stopPropagation();
        let $actionElement = $(this);

        const actionName = $actionElement.attr('data-action-name');
        const selectedItems = $('input[type="checkbox"].form-batch-checkbox:checked');
        modalTitle.text(titleContentWithPlaceholders
            .replace('%action_name%', actionName)
            .replace('%num_items%', selectedItems.length));

        $('#modal-batch-action').modal({backdrop: true, keyboard: true})
            .off('click', '#modal-batch-action-button')
            .on('click', '#modal-batch-action-button', function () {
                $actionElement.unbind('click');

                $form = document.createElement('form');
                $form.setAttribute('action', $actionElement.attr('data-action-url'));
                $form.setAttribute('method', 'POST');

                $actionNameInput = document.createElement('input');
                $actionNameInput.setAttribute('type', 'hidden');
                $actionNameInput.setAttribute('name', 'batchActionName');
                $actionNameInput.setAttribute('value', $actionElement.attr('data-action-name'));
                $form.appendChild($actionNameInput);

                $entityFqcnInput = document.createElement('input');
                $entityFqcnInput.setAttribute('type', 'hidden');
                $entityFqcnInput.setAttribute('name', 'entityFqcn');
                $entityFqcnInput.setAttribute('value', $actionElement.attr('data-entity-fqcn'));
                $form.appendChild($entityFqcnInput);

                $actionUrlInput = document.createElement('input');
                $actionUrlInput.setAttribute('type', 'hidden');
                $actionUrlInput.setAttribute('name', 'batchActionUrl');
                $actionUrlInput.setAttribute('value', $actionElement.attr('data-action-url'));
                $form.appendChild($actionUrlInput);

                $csrfTokenInput = document.createElement('input');
                $csrfTokenInput.setAttribute('type', 'hidden');
                $csrfTokenInput.setAttribute('name', 'batchActionCsrfToken');
                $csrfTokenInput.setAttribute('value', $actionElement.attr('data-action-csrf-token'));
                $form.appendChild($csrfTokenInput);

                selectedItems.each((i, item) => {
                    $entityIdInput = document.createElement('input');
                    $entityIdInput.setAttribute('type', 'hidden');
                    $entityIdInput.setAttribute('name', `batchActionEntityIds[${i}]`);
                    $entityIdInput.setAttribute('value', item.value);
                    $form.appendChild($entityIdInput);
                });

                document.body.appendChild($form);

                //modalTitle.text(titleContentWithPlaceholders);
                $form.submit();
            });
    });
}

function lcCrudIndexInitFilter() {
    $('#filters_form_reset').val('');

    $('.lc-reset-filters').on('click', function (e) {
        //e.preventDefault();
        $(this).parents('.table-filters-line').find('select,input').val('').trigger('change');
        $('#filters_form_reset').val('clearAll');
        Tools.log($(this).prop('form'));
        $(this).prop('form').submit();
        //$(this).parents('form').submit();
    })

}