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

$(function () {
    const table = $('.table-responsive')

    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
    const state: string = $('#state').val() as string

    let url: string = '../../../adm/de/log-login/data' as string

    if (period && state) {
        url = url + '?period=' + period + '&state=' + state
    }
    else if (period) {
        url = url + '?period=' + period
    }
    else if (state) {
        url = url + '?state=' + state
    }

    $('#loginTable').DataTable({
        initComplete: function (settings, json) {
            $('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: "username"},
            {data: "password"},
            {data: "isSuccess"},
            {data: "loginDatetime"},
            {data: "ipAddress"},
            {data: "location"},
        ],
        columnDefs: [
            {
                targets: 6, "createdCell": function (td, cellData, rowData, row, col) {
                    if (!rowData.location) {
                        $(td).html('<span class="float-end"><a href="/adm/de/log-login/geo-data?id=' + rowData.id + '" class="btn btn-primary"><i class="icofont-globe"></i></a></span>');
                    } else {
                        const geoLocation = JSON.parse(rowData.location)
                        $(td).html(geoLocation.country + ', ' + geoLocation.isp + ', ' + geoLocation.zip + ', ' + geoLocation.city)
                    }
                }
            },
            {
                targets: 3, "createdCell": function (td, cellData, rowData, row, col) {
                    if (rowData.isSuccess === false) {
                        $(td).addClass('bg-danger text-white')
                        $(td).text('FAILED')
                    } else {
                        $(td).addClass('bg-success text-white')
                        $(td).text('SUCCESS')
                    }
                }
            },
        ],
    });
})