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

const EXPLORER_STATE_KEY = 'DataTables_explorerTable_v5';

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 () {
    const $table = $('#explorerTable');
    if (!$table.length) {
        return;
    }

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

    $table.DataTable({
        initComplete: function () {
            $('input[type="search"]').first().focus();
        },
        stateSave: true,
        stateSaveCallback: (_settings, data) => {
            try {
                localStorage.setItem(EXPLORER_STATE_KEY, JSON.stringify(data));
            } catch {
                // ignore
            }
        },
        stateLoadCallback: () => {
            try {
                const raw = localStorage.getItem(EXPLORER_STATE_KEY);
                return raw ? JSON.parse(raw) : null;
            } catch {
                return null;
            }
        },
        autoWidth: true,
        paging: true,
        ordering: true,
        order: [[0, 'asc']],
        columnDefs: [
            { targets: [-2, -1], orderable: false, searchable: false },
        ],
    });
});
