let t_med;
const id_medida = document.getElementById('id');
const title = document.getElementById('title');
const btnAccion = document.getElementById('btnAccion');
const nombre = document.getElementById('medida');
const nombre_corto = document.getElementById('nombre_corto');
const form = document.getElementById('formulario');

let active_row=false;
let active_obj=false;

document.addEventListener('DOMContentLoaded', function () {
    //DataTables Medidas - Ajax
    t_med = $('#t_med').DataTable({
        "aPreocesing": true,
        "aServerSide": false,
        "ajax": {
            "url": "" + base_url + "medidas/listar",
            "dataSrc": ""
        },
        "columns": [{ "data": "id" },
        { "data": "medida" },
        { "data": "nombre_corto" },
        { "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_med.on( 'draw', function () {
        $('#t_med tbody tr').removeClass('selected');
        activo_buttons(false)
    } );

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

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

        if($('#t_med 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 + 'medidas/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_medida').modal('hide');
                            t_med.ajax.reload();
                        }

                    }
                }
            }

        }, false);
    });
})

function frmMedida() {
    id_medida.value = '';
    title.textContent = 'Nueva Medida';
    btnAccion.textContent = 'Registrar';
    form.reset();
    $('#nuevo_medida').modal('show');
}

function btnEditarMed(id) {
    title.textContent = 'Modificar Medida';
    btnAccion.textContent = 'Modificar';
    const url = base_url + 'medidas/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_medida.value = res.id;
            nombre.value = res.medida;
            nombre_corto.value = res.nombre_corto;
            $('#nuevo_medida').modal('show');
        }
    }
}

function btnEliminarMed(id) {
    Swal.fire({
        title: 'Esta seguro de eliminar?',
        text: "La medida 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 + "medidas/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_med.ajax.reload();
                    }
                    
                }
            }
        }
    })
}

function btnReingresarMed(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 + "medidas/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_med.ajax.reload();
                    }
                }
            }

        }
    })
} //fin medidas