let t_mar;
const id_marca = document.getElementById('id');
const title = document.getElementById('title');
const btnAccion = document.getElementById('btnAccion');
const nombre = document.getElementById('marca');
const form = document.getElementById('formulario');

let active_row=false;
let active_obj=false;

document.addEventListener('DOMContentLoaded', function () {
    //DataTables Marcas - Ajax
    t_mar = $('#t_mar').DataTable({
        "aPreocesing": true,
        "aServerSide": false,
        "ajax": {
            "url": "" + base_url + "marcas/listar",
            "dataSrc": ""
        },
        "columns": [{ "data": "id" },
        { "data": "marca" },
        { "data": "estado" },
        ],
        "dom": "<'row'<'col-sm-4'l><'col-sm-4 text-center'B><'col-sm-4'f>>" +
            "<'row'<'col-sm-12'tr>>" +
            "<'row'<'col-sm-5'i><'col-sm-7'p>>",
        buttons,
        language,
        "resonsieve": true,
        "bDestroy": true,
        "iDisplayLength": 10,
        "order": [
            [0, "desc"]
        ]
    });

    t_mar.on( 'draw', function () {
        $('#t_mar tbody tr').removeClass('selected');
        activo_buttons(false)
    } );

    $('#t_mar tbody').on( 'click', 'tr', function (e) {
        let classList = e.currentTarget.classList;
       
        if (classList.contains('selected')) {
            classList.remove('selected');
        }
        else {
            t_mar.rows('.selected').nodes().each((row) => row.classList.remove('selected'));
            classList.add('selected');
        }
        activo_buttons( t_mar.row( this ).data()  );
    } );

    function activo_buttons(obj)
    {
        active_obj=obj;
        active_row=active_obj.id;

        if($('#t_mar tbody tr.selected').length==0)
        {
            $('BUTTON.btn-toolbar-status').attr('disabled', 'disabled');
            $('BUTTON.btn-recuperar').hide();
            $('BUTTON.btn-eliminar').show();            
        } else {
            $('BUTTON.btn-toolbar-status').removeAttr('disabled');
            
            if(active_obj.estado_txt==='activo') {
                $('BUTTON.btn-recuperar').hide();
                $('BUTTON.btn-eliminar').show();
            } else {
                $('BUTTON.btn-recuperar').show();
                $('BUTTON.btn-eliminar').hide();
            }            
        }
    }

    var forms = document.getElementsByClassName('needs-validation');
    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function (form) {
        form.addEventListener('submit', function (event) {
            event.preventDefault();
            if (form.checkValidity() === false) {
                event.stopPropagation();
                form.classList.add('was-validated');
            } else {
                const url = base_url + 'marcas/registrar';
                const http = new XMLHttpRequest();
                http.open("POST", url, true);
                http.send(new FormData(this));
                http.onreadystatechange = function () {
                    if (this.readyState == 4 && this.status == 200) {
                        const res = JSON.parse(this.responseText);
                        alertas(res.msg, res.icono);
                        if (res.icono == 'success') {
                            $('#nuevo_marca').modal('hide');
                            t_mar.ajax.reload();
                        }
            
                    }
                }
            }

        }, false);
    });
    
})

function frmMarca() {
    id_marca.value = '';
    title.textContent = 'Nueva Marca';
    btnAccion.textContent = 'Registrar';
    form.reset();
    $('#nuevo_marca').modal('show');
}

function btnEditarMar(id) {
    title.textContent = 'Modificar Marca';
    btnAccion.textContent = 'Modificar';
    const url = base_url + 'marcas/editar/' + id;
    const http = new XMLHttpRequest();
    http.open("GET", url, true);
    http.send();
    http.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            const res = JSON.parse(this.responseText);
            id_marca.value = res.id;
            nombre.value = res.marca;
            $('#nuevo_marca').modal('show');
        }
    }
}

function btnEliminarMar(id) {
    Swal.fire({
        title: 'Esta seguro de eliminar?',
        text: "La marca no se eliminará de forma permanente, solo cambiará el estado a inactivo!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Si!',
        cancelButtonText: 'No'
    }).then((result) => {
        if (result.isConfirmed) {
            const url = base_url + "marcas/eliminar/" + id;
            const http = new XMLHttpRequest();
            http.open("GET", url, true);
            http.send();
            http.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    const res = JSON.parse(this.responseText);
                    alertas(res.msg, res.icono);
                    if (res.icono == 'success') {
                        t_mar.ajax.reload();
                    }
                }
            }
        }
    })
}

function btnReingresarMar(id) {
    Swal.fire({
        title: 'Esta seguro de reingresar?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Si!',
        cancelButtonText: 'No'
    }).then((result) => {
        if (result.isConfirmed) {
            const url = base_url + "marcas/reingresar/" + id;
            const http = new XMLHttpRequest();
            http.open("GET", url, true);
            http.send();
            http.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    const res = JSON.parse(this.responseText);
                    alertas(res.msg, res.icono);
                    if (res.icono == 'success') {
                        t_mar.ajax.reload();
                    }
                }
            }

        }
    })
} //fin marcas