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

window.onload = function(){
    initApp();
    loadListCurrencies();
    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("pairFilter").addEventListener("change", function(){
        loadList(document.getElementById("search").value, selectOrderBy.value, 0, pagerNumber, sessionId);
    });
    document.getElementById("registerFilter").addEventListener("change", function(){
        pagerNumber = parseInt(document.getElementById("registerFilter").value);
        loadList(document.getElementById("search").value, selectOrderBy.value, 0, pagerNumber, sessionId);
    });
    //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);
    });
    document.getElementById("downloadData").addEventListener('click', function(){
        callDownload();
    });
    /*funcion del ordenar**/
     
        var orderDirect = document.getElementById("orderDirect");
        if(orderDirect!==null){
            orderDirect.addEventListener("change",function(){
                document.getElementById("orderBy").dispatchEvent(new Event("change"));
            });
        }
}

function callDownload(){
    var filter =document.getElementById("search").value;
    var currencyid =document.getElementById("pairFilter").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("balances/userscsv?filter="+filter+"&currencyid="+currencyid+"&order="+order+"&sessionid="+sessionId);
    return;
}
//Función para cargar listado
function loadList(filter, order, offset, numofrec, sessionid){
    var par = {};
    var currencyid = document.getElementById("pairFilter").value;
    
    //Se pasa el document.getElementById("search").value por el parametro filter.
        if(filter !== "" && filter !== undefined && filter !== null)
        par.filter = filter;
        
        if(currencyid !== "" && currencyid !== undefined && currencyid !== null)
        par.currencyid = currencyid;
        
        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;
        //Especifico el servicio, los parametros y la funcion de retorno del listado listado
        callWS("GET", "balances/users", 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= "flex";
                            //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 MONEDAS
function loadListCurrencies(){
    var par= {};
    par.order = 1;
    par.offset = 0;
    par.numofrec = 500;
    par.sessionid = sessionId;
        //Especifico el servicio, los parametros y la funcion de retorno del listado listado
    callWS("GET", "currencies/list", par, respListCurrencies);
    return 0;
}
function respListCurrencies(status, rsp){
            let currencies = JSON.parse(rsp);
            var msg = document.getElementById("messageApi");
            switch(status){
                case 200:
                    //console.log(currencies);
                    addOptions("pairFilter",currencies.records);
                    break;
                case 400:
                    console.log(currencies);
                    break;
                case 401:
                    console.log(currencies);
                    break;
                case 500:
                    console.log(currencies);
                    break;
                default:
                    console.log(currencies);
            }
}
function addOptions(domElement, data) {
    var select = document.getElementById(domElement);
    for (let i=0; i<data.length; i++){
        var op = document.createElement("option");
        if(data.length == 0){
            op.text= "No hay monedas definidas";
            op.disabled = true;
            op.value = " ";
            op.selected = true;
            select.add(op);
        } else {
            if(data[i].status.id == 1){
                op.text= data[i].name + "(" + data[i].symbol + ")";
                op.value = data[i].id;
                select.add(op);
            }
        }
    }
}
//Funcion para el Paginado
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 = "";
    for(let k=0; k<pages; 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);
                                
    }
    //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="cell7">'+
                                                    '<div class="divCellCnt">'+
                                                        '<span>'+dataC[i].user.usr+'</span>'+
                                                    '</div>'+
                                                '</div>'+
                                                '<div class="cell1">'+
                                                    '<div class="divCellCnt">'+
                                                        '<span>'+dataC[i].currency.symbol+'</span>'+
                                                    '</div>'+
                                                '</div>'+
                                                '<div class="cell3">'+
                                                    '<div class="divCellCnt">'+
                                                        '<span>'+dataC[i].avaliable+'</span>'+
                                                    '</div>'+
                                                '</div>'+
                                                '<div class="cell4">'+
                                                    '<div class="divCellCnt">'+
                                                        '<span>'+dataC[i].pending+'</span>'+
                                                    '</div>'+
                                                '</div>'+
                                                '<div class="cell5">'+
                                                    '<div class="divCellCnt">'+
                                                        '<span>'+dataC[i].total+'</span>'+
                                                    '</div>'+
                                                '</div>'+
                                                '<div class="cell6">'+
                                                    '<div class="divCellCnt">'+
                                                        '<span>'+dataC[i].last+'</span>'+
                                                    '</div>'+
                                                '</div>';                        
        rowCurrencie.appendChild(tableLine);
    }

}
