import('bootstrap');
import $ from 'jquery';
import 'datatables.net-bs5';

function clearExplorerTableState(): void {
    try {
        Object.keys(localStorage)
            .filter((key) =>
                key.indexOf('DataTables_explorerTable') === 0
                || key.indexOf('DataTables_explorerFilesTable') === 0
            )
            .forEach((key) => localStorage.removeItem(key));
    } catch {
        // ignore
    }
}

$(function () {
    $(document).on('submit', 'form[action*="/explorer/delete"]', () => {
        clearExplorerTableState();
    });

    const $table = $('#explorerFilesTable');
    if (!$table.length) {
        return;
    }

    $table.DataTable({
        initComplete: function () {
            $('input[type="search"]').first().focus();
        },
        stateSave: true,
        autoWidth: true,
        paging: true,
        ordering: true,
        order: [[0, 'asc']],
        columnDefs: [
            { targets: -1, orderable: false, searchable: false },
        ],
    });
});
