//DEVELOP
const PATH_GENERAL = 'http://localhost:7070/Asistencia/';
const PATH_IP = 'http://172.16.2.102:7070/Asistencia/';
//PRODUCCION
const PATH_DOMAIN = '';
const CODIGO_PROYECTO_ASISTENCIA = '7';
//const PATH_SERVICIO_REST = 'http://172.16.2.53:8080/security-rest/api/'//'http://app8.sacooliveros.edu.pe:8080/security-rest/api/';
const PATH_SERVICIO_REST = 'http://app9.sacooliveros.edu.pe:8080/security-rest/api/';

/*Ajax genral*/
const ajaxRequestSendBody = obj => {
    let body = JSON.stringify(obj.body);
    return new Promise((resolve, reject) => {
        $.ajax({
            url: obj.url,
            type: obj.type,
            headers: obj.headers,
            data: {body: body},
            beforeSend: (xhr, settings) => {
            }, success: (response, textStatus, jqXHR) => {
                resolve(response)
            }, error: (jqXHR, textStatus, errorThrown) => {
                reject({
                    status: jqXHR.status,
                    throw: errorThrown || {},
                    jqXHR: jqXHR,
                    request: obj
                })
            }
        })
    })
}
/*Ajax General*/
/*Ajax genral*/
const ajaxRequestGeneral = obj => {
    let body = JSON.stringify(obj.body);
    return new Promise((resolve, reject) => {
        $.ajax({
            url: obj.url,
            type: obj.type,
            headers: obj.headers,
            data: {body: body},
            beforeSend: (xhr, settings) => {
            }, success: (response, textStatus, jqXHR) => {
                resolve(response)
            }, error: (jqXHR, textStatus, errorThrown) => {
                reject({
                    status: jqXHR.status,
                    throw: errorThrown || {},
                    jqXHR: jqXHR,
                    request: obj
                })
            }
        })
    })
}
let createSelectOptions = (obj, valueName, textName) => {
    let options = ''
    obj.forEach((data) => {
        options += `<option value="${data[valueName]}">${data[textName]}</option>`
    })
    return options
}

let customSwal = {
    alert(title, text, type) {
        let colors = {
            success: '#66BB6A',
            error: '#EF5350',
            warning: '#FF7043'
        }
        let btnColor = colors[type]
        return new Promise((resolve, reject) => {
            swal({
                title: title,
                text: text,
                confirmButtonColor: btnColor,
                type: type
            }, (isConfirm) => {
                resolve()
            })
        })
    }
}

/**
 * Get the closest matching element up the DOM tree.
 * @private
 * @param  {Element} elem     Starting element
 * @param  {String}  selector Selector to match against
 * @return {Boolean|Element}  Returns null if not match found
 */
let getClosest = (elem, selector) => {

    // Element.matches() polyfill
    if (!Element.prototype.matches) {
        Element.prototype.matches =
                Element.prototype.matchesSelector ||
                Element.prototype.mozMatchesSelector ||
                Element.prototype.msMatchesSelector ||
                Element.prototype.oMatchesSelector ||
                Element.prototype.webkitMatchesSelector ||
                function (s) {
                    var matches = (this.document || this.ownerDocument).querySelectorAll(s),
                            i = matches.length
                    while (--i >= 0 && matches.item(i) !== this) {
                    }
                    return i > -1
                }
    }
    // Get closest match
    for (; elem && elem !== document; elem = elem.parentNode) {
        if (elem.matches(selector))
            return elem
    }
    return null
}
let block = () => {
    $.blockUI({
        message: '<i class="icon-spinner4 spinner"></i>',
        timeout: 2000, //unblock after 2 seconds
        overlayCSS: {
            backgroundColor: '#1b2024',
            opacity: 0.8,
            cursor: 'wait'
        },
        css: {
            border: 0,
            color: '#fff',
            padding: 0,
            backgroundColor: 'transparent'
        }
    });
}
//let logOut = () =>{
//    document.querySelector('#logOut').addEventListener('click', (e) => {
//        window.location.href = 'http://172.16.2.53:8080/proyecto-estandar/vistas/logout'
//    })
//}
//logOut();

//let logOut = () => {
//    $('.logOut').click(function () {
//        console.log("redireccionando")
//        window.location.href = CONSTANTES.PATH_IP + 'vistas/logout';
//    })
//}

let logOut = () => {
    document.querySelector('#logOut').addEventListener('click', (e) => {
        window.location.href = '../vistas/logout';
    });
};


function defaultConfigDataTable() {
    $.extend($.fn.dataTable.defaults, {
        autoWidth: false,
        searching: false,
        lengthChange: false,
        responsive: true,
        bSort: false,
        dom: '<"datatable-header"fl><"datatable-scroll"t><"datatable-footer"ip>',
        language: {
            "paginate": {
                'first': 'First',
                'last': 'Last',
                'next': '&rarr;',
                'previous': '&larr;'
            },
            "sProcessing": "Procesando...",
            "sLengthMenu": "Mostrar _MENU_ registros",
            "sZeroRecords": "No se encontraron resultados",
            "sEmptyTable": "Ningún dato disponible en esta tabla",
            "sInfo": "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
            "sInfoEmpty": "Mostrando registros del 0 al 0 de un total de 0 registros",
            "sInfoFiltered": "(filtrado de un total de _MAX_ registros)",
            "sInfoPostFix": "",
            "sSearch": "Buscar:",
            "sUrl": "",
            "sInfoThousands": ",",
            "sLoadingRecords": "Cargando...",
            "oPaginate": {
                "sFirst": "Primero",
                "sLast": "Ãšltimo",
                "sNext": "Siguiente",
                "sPrevious": "Anterior"
            },
            "oAria": {
                "sSortAscending": ": Activar para ordenar la columna de manera ascendente",
                "sSortDescending": ": Activar para ordenar la columna de manera descendente"
            }
        },
        drawCallback: function () {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');
        },
        preDrawCallback: function () {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').removeClass('dropup');
        },
        rowCallback: function (row, data, index) {
            if ($(row).hasClass('odd')) {
                $(row).css('background-color', '#e8f4f4');
            }
        }
    });
}



function defaultConfigDatePicker() {
    $.datepicker.regional['es'] = {
        closeText: 'Cerrar',
        prevText: '<Ant',
        nextText: 'Sig>',
        currentText: 'Hoy',
        monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
        monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
        dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
        dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'],
        dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá'],
        weekHeader: 'Sm',
        dateFormat: 'dd/mm/yy',
        firstDay: 1,
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: ''
    };

    $.datepicker.setDefaults($.datepicker.regional['es']);
}


function defaultConfigDateRangePicker() {
    $('.daterange-basic').daterangepicker({
        applyClass: 'bg-slate-600',
//        "singleDatePicker": true,
        cancelClass: 'btn-default',
//        showDropdowns: false,
//        timePicker: true,
//        opens: 'center',
//        singleDatePicker: true,
        autoApply: true,
        locale: {
      format: 'DD/MM/YYYY'
    }
    });
    $('.calendar.right').hide();
}




(function (a) {
    a.fn.validCampo = function (b) {
        a(this).on({keypress: function (a) {
                var c = a.which, d = a.keyCode, e = String.fromCharCode(c).toLowerCase(), f = b;
                (-1 != f.indexOf(e) || 9 == d || 37 != c && 37 == d || 39 == d && 39 != c || 8 == d || 46 == d && 46 != c) && 161 != c || a.preventDefault()
            }})
    }
})(jQuery);
