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

function destroyDataTable(selector: string): void {
    if ($.fn.DataTable.isDataTable(selector)) {
        $(selector).DataTable().destroy();
    }
}

export function initRegistrationTable(): void {
    destroyDataTable('#registrationTable');

    const table = $('.table-responsive');

    table.off('show.bs.dropdown hide.bs.dropdown');
    table.on('show.bs.dropdown', function () {
        $('#registrationTable').css('overflow', 'inherit');
    });
    table.on('hide.bs.dropdown', function () {
        $('#registrationTable').css('overflow', 'auto');
    });

    const period: string = $('#period').val() as string;
    let url: string = '../../../adm/de/registration/data';

    if (period) {
        url = url + '?period=' + period;
    }

    $('#registrationTable').DataTable({
        initComplete: function () {
            $('input[type="search"]').first().focus();
        },
        stateSave: true,
        autoWidth: true,
        paging: true,
        ordering: true,
        order: [[0, 'asc']],
        serverSide: true,
        ajax: {
            url: url,
        },
        columns: [
            { data: 'id' },
            { data: 'company' },
            { data: 'email' },
            { data: 'firstName' },
            { data: 'lastName' },
            { data: 'cellphone' },
            { data: 'regDatetime' },
        ],
    });
}

if (document.getElementById('registrationTable') && !document.getElementById('admDashboardOffcanvasContent')) {
    $(function () {
        initRegistrationTable();
    });
}
