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 MaquinasList {

    constructor() {

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

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

        this.tableMaquinas = null;
        this.deleteModal = null;
    }

    init() {

        const self = this;

        this.headerSearcher();

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

        this.#initTable();

        // Editar en linea la fila
        // Editar en linea la fila
        this.tableMaquinas.table.on('click', '.btn-edit-' + this.tableMaquinas.getAlias(), function (e) {
            
            e.preventDefault(); // Previene cualquier comportamiento por defecto del enlace
        
            const dataId = $(this).closest('tr').find('[data-id]').data('id'); // Obtén el ID dinámico
            const dynamicUrl = '/configuracion/maquinas/edit/' + dataId;
        
            if (!Number.isNaN(Number(dataId))) {
                if (e.ctrlKey || e.metaKey) {
                    // Si se presiona Ctrl (o Cmd en Mac), abrir en una nueva pestaña
                    window.open(dynamicUrl, '_blank');
                } else {
                    // Navegar normalmente en la misma pestaña
                    window.location.href = dynamicUrl;
                }
            } else {
                console.error('ID no válido:', dataId);
            }
        });

        // Eliminar la fila
        this.tableMaquinas.table.on('click', '.btn-delete-' + this.tableMaquinas.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(
                        '/maquinas/delete/' + dataId,
                        {

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

                            self.tableMaquinas.table.clearPipeline();
                            self.tableMaquinas.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': 'nombre' },
            { 'data': 'tipo' },
            { 'data': 'ancho_impresion',render : (d) => `<span class="autonumeric">${d}</span>` },
            { 'data': 'alto_impresion',render : (d) => `<span class="autonumeric">${d}</span>` },
            { 'data': 'min',render : (d) => `<span class="autonumeric">${d}</span>` },
            { 'data': 'max',render : (d) => `<span class="autonumeric">${d}</span>` }
        ];

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

        this.tableMaquinas = new Table(
            $('#tableOfMaquinas'),
            'maquinasList',
            '/configuracion/maquinas/datatable',
            columns,
            []
        );


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


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

    }

    headerSearcher() {

        const self = this;

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

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

                let min_width = 100;
                if (i == 0) {
                    min_width = 50;
                }

                if (i == 2) {

                    // Agregar un selector en la segunda columna
                    $(this).html('<select class="form-control" style="min-width:100px;max-width:120px;font-size:0.8rem !important;"></select>');

                    // Agregar opciones al selector
                    var selector = $('select', this);
                    selector.append('<option value="">Todos</option>'); // Opción vacía
                    selector.append('<option value="acabado">Acabado</option>');
                    selector.append('<option value="manipulado">Manupulado</option>');
                    selector.append('<option value="impresion">Impresión</option>');

                    selector.on('change', function () {
                        var val = $.fn.dataTable.util.escapeRegex(
                            $(this).val()
                        );
                        self.tableMaquinas.table.column(i).search(val).draw();
                    });

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

                    $('input', this).on('change clear', function () {
                        if (self.tableMaquinas.table.column(i).search() !== this.value) {
                            self.tableMaquinas.table
                                .column(i)
                                .search(this.value)
                                .draw();
                        }
                    });
                }


            }
            else {
                $(this).html('<span></span>');
            }
        });


    }

}

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

    const dropdown = document.querySelector(".dropdown-language");
    const activeItem = dropdown.querySelector(".dropdown-menu .dropdown-item");
    let locale = 'es';
    if (activeItem) {
        locale = activeItem.getAttribute("data-language");
    }

    new Ajax('/translate/getTranslation', { locale: locale, translationFile: ['Maquinas'] }, {},
        function (translations) {
            window.language = JSON.parse(translations);
            new MaquinasList().init();
        },
        function (error) {
            console.log("Error getting translations:", error);
        }
    ).post();
});

