//Variables globales
var cleared=null;
var sessionId = sessionStorage.getItem("sessionId");
var pagerNumber = 10;

window.onload = function(){
    initApp();
    loadListModuls();
    loadList(document.getElementById("search").value, 1, 0, pagerNumber, sessionId);
    
    var selectOrderBy = document.getElementById("orderBy");
    selectOrderBy.addEventListener("change", function(){
        loadList(document.getElementById("search").value, selectOrderBy.value, 0, pagerNumber, sessionId);
    });
    document.getElementById("addDate").addEventListener("blur", function(){
        // Fecha desde
        // Validamos que sea menor o igual a la fecha final
        
        if(document.getElementById('addDate1').value == ''){
            loadList(document.getElementById("search").value, selectOrderBy.value, 0, pagerNumber, sessionId);
        }else{
            if(this.value <= document.getElementById('addDate1').value ){
                loadList(document.getElementById("search").value, selectOrderBy.value, 0, pagerNumber, sessionId);
            }else{
                let msg = document.getElementById('messageApi');
                /*Blanquear tabla*/
                            var nodeNoDelete = document.getElementById("noCurrencieDefine");
                            if (nodeNoDelete ){
                                var nodeClone = nodeNoDelete.cloneNode(true);   
                                nodeClone.style.display="none";
                            }
                            var table = document.getElementById("bodyTableCurrencies");
                            table.innerHTML = "";
                            if(nodeClone!==undefined && nodeClone!==null){
                                table.appendChild(nodeClone);
                            }
                            document.getElementById("paginator").style.display= "none";
                            
                msg.innerHTML="Fecha inicial debe ser menor o igual a la fecha final";
                msg.classList.add("msgError"); 
                msg.style.display="block";
                setTimeout(function() {
                    msg.classList.remove("msgError"); 
                    msg.style.display="none";
                }, 3000);
            }
        }
    });
    document.getElementById("addDate1").addEventListener("blur", function(){
        // Fecha hasta
        // Validamos que sea mayor o igual a la otra fecha inicial
        
        if( document.getElementById("addDate").value == '' ){
            loadList(document.getElementById("search").value, selectOrderBy.value, 0, pagerNumber, sessionId);
        }else{
            if(this.value >= document.getElementById("addDate").value){
                loadList(document.getElementById("search").value, selectOrderBy.value, 0, pagerNumber, sessionId);
            }else{
                let msg = document.getElementById('messageApi');
                
                /*Blanquear tabla*/
                            var nodeNoDelete = document.getElementById("noCurrencieDefine");
                            if (nodeNoDelete ){
                                var nodeClone = nodeNoDelete.cloneNode(true);   
                                nodeClone.style.display="none";
                            }
                            var table = document.getElementById("bodyTableCurrencies");
                            table.innerHTML = "";
                            if(nodeClone!==undefined && nodeClone!==null){
                                table.appendChild(nodeClone);
                            }
                            document.getElementById("paginator").style.display= "none";
                
                msg.innerHTML="Fecha final debe ser mayor o igual a la fecha inicial";
                msg.classList.add("msgError"); 
                msg.style.display="block";
                setTimeout(function() {
                    msg.classList.remove("msgError"); 
                    msg.style.display="none";
                }, 3000);
            }
        }
    });
    document.getElementById("modulFilter").addEventListener("change", function(){
        loadList(document.getElementById("search").value, selectOrderBy.value, 0, pagerNumber, sessionId);
    });
    document.getElementById("cmsFilter").addEventListener("change", function(){
        loadList(document.getElementById("search").value, selectOrderBy.value, 0, pagerNumber, sessionId);
        loadListModuls();
    });
    //Asignar evento barra de busqueda
    document.getElementById("search").addEventListener("change",function(){
        loadList(this.value, document.getElementById("orderBy").value, 0, pagerNumber, sessionId);
    });
    document.getElementById("search").addEventListener("keyup",function(e){
        if(e.keyCode==13)loadList(this.value, document.getElementById("orderBy").value, 0, pagerNumber, sessionId);
    });
    //BUSQUEDA INTELIGENTE
    document.getElementById("searchUser").addEventListener("keyup", function(e){
            
            if(this.value.length >= 3){
                    if(cleared !== null){
                        clearTimeout(cleared);
                    }
                    cleared= setTimeout(function(){ myUsers(document.getElementById("searchUser").value); }, 1000);
            }else if(e.keyCode == 8){
                document.getElementById("searchUser").value="";
                
                if(cleared !== null){
                    clearTimeout(cleared);
                }
            }
    });
    window.addEventListener("click", function(){ 
        var div=document.getElementById("searchResult");
            div.classList.add("noShow");
    });
    
    
     /*funcion del ordenar**/
     
        var orderDirect = document.getElementById("orderDirect");
        if(orderDirect!==null){
            orderDirect.addEventListener("change",function(){
                document.getElementById("orderBy").dispatchEvent(new Event("change"));
            });
        }
    
    //FIN BUSQUEDA
    document.getElementById("downloadData").addEventListener('click', function(){
        callDownload();
    });
    

}



//************* BUSQUEDA INTELIGENTE *******************
function myUsers(value){
    var par = {};
    par.filter = value;
    par.offset = 0;
    par.order = "1";
    par.numofrecords = 2000;
    par.sessionid = sessionId;
    callWS("GET", "appusers/list", par, rspUser);
    return 0;
}
function rspUser(status, rsp){
        switch(status){
            case 200:
               // console.log(JSON.parse(rsp));
                var resp=JSON.parse(rsp);
                var lista=document.getElementById("resultsC");
                var div=document.getElementById("searchResult");
                div.classList.remove("noShow");
                mySearchAddUser(lista,resp.records,resp.numofrecords);
                break;
            case 400:
                console.log(JSON.parse(rsp));
                break;
            case 401:
                msg.innerHTML="Sesión expirada o inválida, vuelva a iniciar sesión";
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        myLogout()
                        msg.style.display="none";
                    }, 3000);
                    break;
            case 403:
                console.log(JSON.parse(rsp));
                break;
            case 500:
                var resSeller=JSON.parse(rsp);
                alert("Error 500 "+resSeller.msg);
                console.log(JSON.parse(rsp));
                break;
            default:
                //console.log(rsp);
        }
}
function mySearchAddUser(lista,data,num){
    lista.innerHTML = "";
    if(num===0){
      var line = document.createElement("li"); 
      line.innerHTML ='<span class="smallRsp">No tenemos registros que coincidan con su busqueda.</span>';
      lista.appendChild(line);
    }else{
        for(navLink of data){
            var line = document.createElement("li");
            line.classList.add("myNewLineUser");
            line.id="user-"+navLink.id;
            line.innerHTML ='<p class="nameResult"> '+navLink.usr+'</p>';
                lista.appendChild(line);
        }  
    }
    document.querySelectorAll('[class="myNewLineUser"]').forEach(function (element) {
       element.addEventListener('click', function (event) {
         var id=element.id;
         var par = {};
                par.id = parseInt(id.split("-")[1]);
                par.sessionid = sessionId;
                callWS("GET", "appusers/entry", par, rspUserEntry);
                return 0;
        }); 
    });
}
function rspUserEntry(status, rsp){
    switch(status){
        case 200:
            console.log(JSON.parse(rsp));
            var resp=JSON.parse(rsp).entry;
            var inputUser= document.getElementById("searchUser");
            inputUser.value=resp.usr;
            loadList(document.getElementById("search").value, document.getElementById("orderBy").value, 0, pagerNumber, sessionId);
            break;
        case 400:
            console.log(JSON.parse(rsp));
            break;
        case 401:
            msg.innerHTML="Sesión expirada o inválida, vuelva a iniciar sesión";
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        myLogout()
                        msg.style.display="none";
                    }, 3000);
                    break;
        case 403:
            console.log(JSON.parse(rsp));
            break;
        case 500:
            var resSeller=JSON.parse(rsp);
            console.log(JSON.parse(rsp));
            break;
        default:
            //console.log(rsp);
    }
}
function callDownload(){
    var filter =document.getElementById("search").value;
    var modul =document.getElementById("modulFilter").value;
    var order = document.getElementById("orderBy").value;
    order = Math.abs(order);
    var dir = document.getElementById("orderDirect").value;
    if(dir=="desc")order="-"+order;
    order = order;

    download("audit/listcsv?filter="+filter+"&modul="+modul+"&order="+order+"&sessionid="+sessionId);
    return;
}

//Función para cargar listado
function loadList(filter, order, offset, numofrec, sessionid){
    var par = {};
    var modul = document.getElementById("modulFilter").value;
    var appid = document.getElementById("cmsFilter").value;
    var date = document.getElementById("addDate").value;
    var date1 = document.getElementById("addDate1").value;
    var user = document.getElementById("searchUser").value ;
    //Se pasa el document.getElementById("search").value por el parametro filter.
        if(filter !== "" && filter !== undefined && filter !== null)
        par.filter = filter;
        if(modul !== "" && modul !== undefined && modul !== null)
        par.modul = modul;
        if(user !== "" && user !== undefined && user !== null)
        par.user = user;
        if(date !== "" && date !== undefined && date !== null)
        par.datefrom = date;
        if(date1 !== "" && date1 !== undefined && date1 !== null)
        par.dateto = date1;
        var order = Math.abs(order);
        var dir = document.getElementById("orderDirect").value;
        if(dir=="desc")order="-"+order;
        par.order = order;
        par.offset = offset;
        par.numofrec = numofrec;
        par.sessionid = sessionid;
        par.appid = appid;
        console.log(par)
        //Especifico el servicio, los parametros y la funcion de retorno del listado listado
        callWS("GET", "audit/list", par, respList);
        return 0;
}
//Función para el retorno del listado listado
function respList(status, rsp){
            let currencies = JSON.parse(rsp);
            var msg = document.getElementById("messageApi");
            switch(status){
                case 200:
                    //console.log(currencies);

                        if (currencies.numofrecords === 0){
                            /*Blanquear tabla*/
                            var nodeNoDelete = document.getElementById("noCurrencieDefine");
                            if (nodeNoDelete ){
                                var nodeClone = nodeNoDelete.cloneNode(true);   
                                nodeClone.style.display="none";
                            }
                            var table = document.getElementById("bodyTableCurrencies");
                            table.innerHTML = "";
                            if(nodeClone!==undefined && nodeClone!==null){
                                table.appendChild(nodeClone);
                            }
                            /**-hasta aqui-**/
                            //document.getElementById("noCurrencieDefine").style.display = "block";
                            //document.getElementById("msgInTable").innerHTML="No Posee Balances definidos";
                            document.getElementById("paginator").style.display= "none";
                        }else{
                            if(currencies.numofrecords <= pagerNumber){
                                document.getElementById("paginator").style.display= "none";    
                            } else {
                                document.getElementById("paginator").style.display= ""; 
                                drawPags(currencies.numofrecords, "numbersPaginator");
                            }
                            /*Blanquear tabla*/
                            var nodeNoDelete = document.getElementById("noCurrencieDefine");
                            if (nodeNoDelete ){
                                var nodeClone = nodeNoDelete.cloneNode(true);   
                                nodeClone.style.display="none";
                            }
                           var table = document.getElementById("bodyTableCurrencies");
                            table.innerHTML = "";
                            if(nodeClone!==undefined && nodeClone!==null)table.appendChild(nodeClone);
                            /**-hasta aqui-**/
                            //Pintar registros
                            paintRowsList(currencies);
                     }
                    break;
                case 400:
                    msg.innerHTML=currencies.msg;
                    msg.classList.add("msgError");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError");   
                        msg.style.display="none";
                    }, 5000);
                    break;
                    break;
                case 401:
                    msg.innerHTML="Sesión expirada o inválida, vuelva a iniciar sesión";
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        myLogout()
                        msg.style.display="none";
                    }, 3000);
                    break;
                case 500:
                    msg.innerHTML=" Error Interno";
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        msg.style.display="none";
                    }, 3000);
                    break;
                default:
                    msg.innerHTML=currencies.msg;
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        msg.style.display="none";
                    }, 3000);
            }
}
//Función para cargar listado MODULOS
function loadListModuls(){
    //console.log("hola");
    var par= {};
    var appid = document.getElementById("cmsFilter").value;
    par.sessionid = sessionId;
    par.appid = appid;
        //Especifico el servicio, los parametros y la funcion de retorno del listado listado
    callWS("GET", "moduls/list", par, respListModuls);
    return 0;
}
function respListModuls(status, rsp){
            let currencies = JSON.parse(rsp);
            var msg = document.getElementById("messageApi");
            switch(status){
                case 200:
                    console.log(currencies);
                    if(currencies.records!==null)addOptions("modulFilter",currencies.records);
                    break;
                case 400:
                    console.log(currencies);
                    break;
                case 401:
                    msg.innerHTML="Sesión expirada o inválida, vuelva a iniciar sesión";
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        myLogout()
                        msg.style.display="none";
                    }, 3000);
                    break;
                case 500:
                    console.log(currencies);
                    break;
                default:
                    console.log(currencies);
            }
}
function addOptions(domElement, data) {
 var select = document.getElementById(domElement);
 select.innerHTML = '<option value="" selected style="font-size: 13px">Módulos</option>';
    for (i = 0; i < data.length; i++) {
        var option = document.createElement("option");
        option.value = data[i].dsc;
        option.text = data[i].dsc;
        select.add(option);
    }
}
//Funcion para el Paginado
var pagerNumber = 10;
function drawPags(numofrecords, tbl){
    var pages = Math.ceil( numofrecords / pagerNumber );
    var numbersPaginator = document.getElementById(tbl);
    var lastPag = 0;
    if(numbersPaginator.getElementsByClassName("pSelect").length>0){
        lastPag = numbersPaginator.getElementsByClassName("pSelect")[0].getAttribute("data-page");
    }
    numbersPaginator.innerHTML = "";
    
    var initialPage=0;
    var n=8;
    if (pages>n){  // cambio de formato en caso de mas de n paginas
        initialPage = Math.max((lastPag-Math.ceil(n/2)+2), 1)-1;
    }
    
    // puntitos iniciales cuando son más de 10 página y no se empieza por la primera
    if (pages>n && initialPage !== 0 && initialPage !== 1){
        spanF = document.createElement("div");
        spanF.classList.add("pages");
        spanF.innerHTML = "1 ...";
        spanF.dataset.page= 1;
        spanF.style.cursor="pointer";
        spanF.addEventListener("click", function(){
            //Se desmarca la página anterior
            var pSel = document.getElementsByClassName("pSelect");
            if(pSel.length>0)pSel[0].classList.remove("pSelect");
            
            //Se actualiza la página seleccionada
            this.classList.add("pSelect");
            
            //Se repinta el listado desde el offset seleccionado
            var offset = (this.getAttribute("data-page")-1)*pagerNumber;
            var order = document.getElementById("orderBy").value;
            var filter = document.getElementById("search").value;
            loadList(filter, order, offset, pagerNumber, sessionStorage.getItem("sessionId"));
        });
        numbersPaginator.appendChild(spanF);
        /*
        span = document.createElement("div");
        span.classList.add("pages");
        span.innerHTML = "...";
        numbersPaginator.appendChild(span);*/
        
    }

    //Pintar paginas de table (numeros)
    for(var k=initialPage; k<pages && !(k-initialPage > n-1); k++){
        var p = document.createElement("div");
        p.classList.add("pages");
        p.innerHTML = k+1;
        p.dataset.page= k+1;
        if(lastPag==0 && k==0)p.classList.add("pSelect");//Se selecciona la página 1
        else if(lastPag!==0 && (lastPag-1)==k)p.classList.add("pSelect");
        
        p.addEventListener("click", function(){
            //Se desmarca la página anterior
            var pSel = document.getElementsByClassName("pSelect");
            if(pSel.length>0)pSel[0].classList.remove("pSelect");
            
            //Se actualiza la página seleccionada
            this.classList.add("pSelect");
            
            //Se repinta el listado desde el offset seleccionado
            var offset = (this.innerHTML-1)*pagerNumber;
            var order = document.getElementById("orderBy").value;
            var filter = document.getElementById("search").value;
            loadList(filter, order, offset, pagerNumber, sessionStorage.getItem("sessionId"));
        });
        p.style.cursor="pointer";
        numbersPaginator.appendChild(p);
                                
    }
    
    // puntitos si no se ven las útlimas páginas
    if (pages>n && initialPage+n<pages){
        /*
        span = document.createElement("div");
        span.setAttribute("title", pages+" páginas")
        span.classList.add("pages");
        span.innerHTML = "...";
        numbersPaginator.appendChild(span);
        */
        
        spanL = document.createElement("div");
        spanL.classList.add("pages");
        spanL.innerHTML = "... "+pages;
        spanL.dataset.page= pages;
        spanL.style.cursor="pointer";
        spanL.addEventListener("click", function(){
            //Se desmarca la página anterior
            var pSel = document.getElementsByClassName("pSelect");
            if(pSel.length>0)pSel[0].classList.remove("pSelect");
            
            //Se actualiza la página seleccionada
            this.classList.add("pSelect");
            
            //Se repinta el listado desde el offset seleccionado
            var offset = (this.getAttribute("data-page")-1)*pagerNumber;
            var order = document.getElementById("orderBy").value;
            var filter = document.getElementById("search").value;
            loadList(filter, order, offset, pagerNumber, sessionStorage.getItem("sessionId"));
        });
        numbersPaginator.appendChild(spanL);
    }
    
    
    
    //Asignación de eventos validar que sólo se haga una vez
    if(numbersPaginator.getAttribute("arrowsEvent")=="false"){
        var leftArrow = numbersPaginator.previousElementSibling;
        var rightArrow = numbersPaginator.nextElementSibling;
        //Evento flecha izquierda
        leftArrow.addEventListener("click",function(){
            var pSel = document.getElementsByClassName("pSelect");
            if(pSel.length>0){
                //Si el elemento anterior al seleccionado es una pagina
                if(pSel[0].previousElementSibling.classList.contains("pages")){
                    var last = pSel[0];
                    pSel[0].previousElementSibling.classList.add("pSelect");
                    last.classList.remove("pSelect");
                    //Se repinta el listado desde el offset seleccionado
                    var offset = (pSel[0].innerHTML-1)*pagerNumber;
                    var order = document.getElementById("orderBy").value;
                    var filter = document.getElementById("search").value;
                    loadList(filter, order, offset, pagerNumber, sessionStorage.getItem("sessionId"));
                }
            }
        });
        //Evento flecha derecha
        rightArrow.addEventListener("click",function(){
            var pSel = document.getElementsByClassName("pSelect");
            if(pSel.length>0){
                //Si el elemento anterior al seleccionado es una pagina
                if(pSel[0].nextElementSibling.classList.contains("pages")){
                    pSel[0].nextElementSibling.classList.add("pSelect");
                    pSel[0].classList.remove("pSelect");
                    
                    //Se repinta el listado desde el offset seleccionado
                    var offset = (pSel[0].innerHTML-1)*pagerNumber;
                    var order = document.getElementById("orderBy").value;
                    var filter = document.getElementById("search").value;
                    loadList(filter, order, offset, pagerNumber, sessionStorage.getItem("sessionId"));
                }
            }
        });
        numbersPaginator.setAttribute("arrowsEvent",true);
    }
    
    
}


//Aqui se pintan los registros
function paintRowsList(data){
    var pageInPaginator = document.getElementsByClassName("pSelect")[0];
    if(pageInPaginator){
        pageInPaginator = pageInPaginator.innerHTML;
    }
    var rowCurrencie = document.getElementById("bodyTableCurrencies");
    rowCurrencie.innerHTML = "";
    var filas;
    if (data.numofrecords > pagerNumber){
        filas = parseInt(data.numofrecords) - ((parseInt(pageInPaginator) - 1) * pagerNumber);
        if(filas > pagerNumber){
            filas = pagerNumber;
        }
    } else {
        filas = data.numofrecords
    }
    
    
    //type 0 = impar, 1 = par
    let type = 0;
    let dataC = data.records;
    for (let i=0; i<filas; i++){
        var tableLine = document.createElement("div");
        tableLine.classList.add("tableLine");
        tableLine.id= "line/"+dataC[i].id;
        if(type === 0){
            tableLine.classList.add("rowImpar");
            type=type+1;
        }else if(type === 1){
            type = 0;
        }
        tableLine.innerHTML = '<div class="cell1">'+
                                                    '<div class="divCellCnt">'+
                                                        '<span>'+dataC[i].date.formatted+'</span>'+
                                                    '</div>'+
                                                '</div>'+
                                                '<div class="cell2">'+
                                                    '<div class="divCellCnt">'+
                                                        '<span>'+dataC[i].user.email+'</span>'+
                                                    '</div>'+
                                                '</div>'+
                                                '<div class="cell3">'+
                                                    '<div class="divCellCnt">'+
                                                        '<span>'+dataC[i].modul+'</span>'+
                                                    '</div>'+
                                                '</div>'+
                                                '<div class="cell4">'+
                                                    '<div class="divCellCnt">'+
                                                        '<span>'+dataC[i].dsc+'</span>'+
                                                    '</div>'+
                                                '</div>';
        rowCurrencie.appendChild(tableLine);
    }

}
