import Table from '../../components/table.js';
import ConfirmDeleteModal from '../../components/ConfirmDeleteModal.js';
import Ajax from '../../components/ajax.js';
import { getToken } from '../../common/common.js';

class UserList {

    constructor() {

        this.domItem = $('.card-body');

        this.csrf_token = getToken();
        this.csrf_hash = $('#mainContainer').find('input[name="' + this.csrf_token + '"]').val();

        this.tableUsers = null;
        this.deleteModal = null;
    }

    init() {

        const self = this;

        this.headerSearcher();

        this.deleteModal = new ConfirmDeleteModal('plantillasTarifasCliente');
        this.deleteModal.init();

        this.#initTable();

        // Editar en linea la fila
        this.tableUsers.table.on('click', '.btn-edit-' + this.tableUsers.getAlias(), function (e) {

            const dataId = $(this).attr('data-id');

            if (!Number.isNaN(Number(dataId))) {
                window.location.href = '/users/edit/' + dataId;
            }
        });


        // Eliminar la fila
        this.tableUsers.table.on('click', '.btn-delete-' + this.tableUsers.getAlias(), function (e) {
            const row = $(this).closest('tr')[0]._DT_RowIndex;
            const dataId = $(this).attr('data-id');
            self.deleteModal.setData($(this).attr('data-id'));
            self.deleteModal.show(() => {

                if (!Number.isNaN(Number(self.deleteModal.getData()))) {

                    new Ajax(
                        '/users/delete/' + dataId,
                        {

                        },
                        {},
                        (data, textStatus, jqXHR) => {

                            self.tableUsers.table.clearPipeline();
                            self.tableUsers.table.row($(row)).invalidate().draw();

                            popSuccessAlert(data.msg ?? jqXHR.statusText);
                        },
                        (error) => {
                            console.log(error);
                        }

                    ).get();
                    self.deleteModal.hide();
                }
            });
        });
    }

    #initTable() {

        const self = this;

        const columns = [
            { 'data': 'id' },
            { 'data': 'first_name' },
            { 'data': 'last_name' },
            { 'data': 'email' },
            { 'data': 'cliente' },
            { 'data': 'last_active' },
        ];

        const actions = ['edit', 'delete'];

        this.tableUsers = new Table(
            $('#tableOfUsers'),
            'users',
            '/users/datatable',
            columns,
            []
        );


        this.tableUsers.init({
            actions: actions,
            colVisibility: false,
            buttonsExport: true,
        });


        this.tableUsers.table.on('init.dt', function () {
            self.tableUsers.table.page.len(50).draw();
        });

    }

    headerSearcher() {

        const self = this;

        $('#tableOfUsers thead tr').clone(false).appendTo('#tableOfUsers thead');
        $('#tableOfUsers thead tr:eq(1) th').each(function (i) {

            if (!$(this).hasClass("noFilter")) {

                $(this).html('<input type="text" class="form-control " style="min-width:100px;max-width:500px;font-size:0.8rem !important;"  />');

                $('input', this).on('change clear', function () {
                    if (self.tableUsers.table.column(i).search() !== this.value) {
                        self.tableUsers.table
                            .column(i)
                            .search(this.value)
                            .draw();
                    }
                });
            }
            else {
                $(this).html('<span></span>');
            }
        });


    }

}

document.addEventListener('DOMContentLoaded', function () {

    new UserList().init();
}); 
