var sessionId = sessionStorage.getItem("sessionId");
let editor;
let editor2;
window.onload = function(){
    initApp();
    changebutt();//Asignación de eventos 
    entryLevel();//Detalles
} 
function changebutt(){
    document.getElementById("currency").addEventListener("click", function(){
        document.querySelectorAll('[class^="buttonchange"]').forEach(function (elmt) {
            elmt.classList.remove("activeTab");
        });
        document.querySelectorAll('[class^="SuperContainer"]').forEach(function (element) {
            element.classList.add("nShow");
        });
        this.classList.add("activeTab");
        document.getElementById("sectionCurrency").classList.remove("nShow");
    })
    document.getElementById("pair").addEventListener("click", function(){
        document.querySelectorAll('[class^="buttonchange"]').forEach(function (elmt) {
            elmt.classList.remove("activeTab");
        });
        document.querySelectorAll('[class^="SuperContainer"]').forEach(function (element) {
            element.classList.add("nShow");
        });
        this.classList.add("activeTab");
        document.getElementById("sectionPair").classList.remove("nShow");
    });
}
var reloadEntry = true;
function entryLevel(){
var par = {};
    par.sessionid = sessionId;
    callWS("GET", "accounting/accounts", par, rspAccEntry);
    return 0;
}
function rspAccEntry(status, rsp){
    switch(status){
        case 200:
            var resp = JSON.parse(rsp);
            if(resp.privileges.read){
                paintPerCurr(resp.currency,resp.privileges.update);
                paintPerPair(resp.pair,resp.privileges.update);
            
                var btnsel = document.getElementsByClassName("activeTab");
                if(btnsel.length>0)btnsel[0].dispatchEvent(new Event("click"));
                else{
                    document.getElementsByClassName("buttonchange")[0].dispatchEvent(new Event("click"));
                }
                
            }else{
                var msg = document.getElementById("messageError");
                msg.innerHTML= "No posee privilegios de lectura";
                msg.classList.add("msgError"); 
                msg.style.display="block";
            }
            setTimeout(function() {
                reloadEntry = true;
            }, 4000);

            break;
        case 400:
            console.log(JSON.parse(rsp));
            break;
        case 401:
            var msg = document.getElementById("messageError");
            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:
            var msg = document.getElementById("messageError");
            msg.innerHTML= "No posee privilegios de lectura";
            msg.classList.add("msgError"); 
            msg.style.display="block";
            break;
        case 500:
            var resSeller=JSON.parse(rsp);
            console.log(JSON.parse(rsp));
            break;
        default:
            console.log(rsp);
    }
}

function setLang(elementSelect, group, borderSide = ""){
    let selectedEl = document.getElementsByClassName('selectedLang');
    
    if(selectedEl.length > 0){
        Array.prototype.forEach.call(selectedEl, function(el) {
            //console.log(el);
            if(el.getAttribute('data-group') == group){
                el.classList.remove("selectedLang");
            }
        });
    }
    
    
    document.getElementById(elementSelect).classList.add("selectedLang");
    
    if(borderSide != ""){
        
        if(borderSide == 'right'){
            document.getElementById(elementSelect).style.borderBottomRightRadius = "10px";
            document.getElementById(elementSelect).style.borderTopRightRadius = "10px";
        }else{
            document.getElementById(elementSelect).style.borderBottomLeftRadius = "10px";
            document.getElementById(elementSelect).style.borderTopLeftRadius = "10px";
        }
        
    }
}
function rspUserSaveLevel(status, rsp){
    switch(status){
        case 200:
            //console.log(JSON.parse(rsp));
            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 paintPerCurr(data,priv){
    console.log(data);
    var i=0;
    document.getElementById("currTab").innerHTML = "";
    document.getElementById("overflowX").innerHTML = "";
    var list = [];
    var dataType = [];
    dataType = data.types;
    
    //Primera columna de tipos
    for (datos of dataType){
        //Crear contendor por grupo de tipos
        var cnt = document.createElement("div");
        cnt.classList.add("currencytypes");
        
        //Dsc primer tipo de titulo
        var desc = document.createElement("div"); 
        desc.classList.add("currencyBold");
        desc.innerHTML = '<span>'+datos.dsc+'</span>';
        cnt.appendChild(desc);
        //Agregar sub tipos
        var subtypes = datos.subtypes;
        for(types of subtypes){
            var subt = document.createElement("div"); 
            subt.classList.add("currencyTab");
            subt.innerHTML = '<span>'+types.dsc+'</span>';
            cnt.appendChild(subt);
        }
        
        document.getElementById("currTab").appendChild(cnt);
    }
    
    var currencies = [];
    currencies = data.currencies;
    //Insertar tantas columnas a la derecha cómo monedas existan
    for (currency of currencies){
        var columnCurr = document.createElement("div");
        columnCurr.classList.add("currCol");
        for(types of dataType){
            //Crear contendor por grupo de tipos
            var cnt = document.createElement("div");
            cnt.classList.add("currencytypes");
            
            if((i%2)!==0)cnt.classList.add("currencyBg1");
            else cnt.classList.add("currencyBg2");
            
            //Dsc de la moneda primera linea
            var desc = document.createElement("div"); 
            desc.classList.add("currencyTab","currencyHead");
            desc.innerHTML = '<span>'+currency.symbol+'</span>';
            cnt.appendChild(desc);
            
            for(subtype of types.subtypes){
                //Agregar las cuentas según los sub-tipos
                
                var subt = document.createElement("input"); 
                subt.classList.add("currencyInpt");
                    
                var accounts = currency.accounts;
                for(acc of accounts){
                    if(acc.subtype.id == subtype.id){
                        subt.value = acc.dsc;//acc.subtype.dsc;
                        subt.setAttribute("accid",acc.id);
                        //Cuando se actualiza el campo se dispara el guardar
                        subt.addEventListener("change",function(){
                            if(priv){
                                saveAccount(this.getAttribute("accid"),this.value); 
                            }else{
                                var msg = document.getElementById("messageError");
                                msg.innerHTML= "No posee privilegios para modificar cuentas contables";
                                msg.classList.add("msgError"); 
                                msg.style.display="block";
                                setTimeout(function() {
                                    msg.classList.remove("msgError");   
                                    msg.style.display="none";
                                    entryLevel();
                                }, 3000);
                            }
                        });
                    }
                }
                if(subt.getAttribute("accid")==undefined || subt.getAttribute("accid")=="" || subt.getAttribute("accid")==null)subt.setAttribute("disabled","");
                cnt.appendChild(subt);
            }
            
            columnCurr.appendChild(cnt);
        }
        i++;
        document.getElementById("overflowX").appendChild(columnCurr);
    }
}
function paintPerPair(data,priv){
    var i=0;
    document.getElementById("pairTab").innerHTML = "";
    document.getElementById("overflowXPair").innerHTML = "";
    var list = [];
    var dataType = [];
    dataType = data.types;
    
    //Primera columna de tipos
    for (datos of dataType){
        //Crear contendor por grupo de tipos
        var cnt = document.createElement("div");
        cnt.classList.add("currencytypes");
        
        //Dsc primer tipo de titulo
        var desc = document.createElement("div"); 
        desc.classList.add("currencyBold");
        desc.innerHTML = '<span>'+datos.dsc+'</span>';
        cnt.appendChild(desc);
        //Agregar sub tipos
        var subtypes = datos.subtypes;
        for(types of subtypes){
            var subt = document.createElement("div"); 
            subt.classList.add("currencyTab");
            subt.innerHTML = '<span>'+types.dsc+'</span>';
            cnt.appendChild(subt);
        }
        
        document.getElementById("pairTab").appendChild(cnt);
    }
    
    var currencies = [];
    currencies = data.pairs;
    //Insertar tantas columnas a la derecha cómo monedas existan
    for (currency of currencies){
        var columnCurr = document.createElement("div");
        columnCurr.classList.add("currCol");
        for(types of dataType){
            //Crear contendor por grupo de tipos
            var cnt = document.createElement("div");
            cnt.classList.add("currencytypes");
            
            if((i%2)!==0)cnt.classList.add("currencyBg1");
            else cnt.classList.add("currencyBg2");
            
            //Dsc de la moneda primera linea
            var desc = document.createElement("div"); 
            desc.classList.add("currencyTab","currencyHead");
            desc.innerHTML = '<span>'+currency.name+'</span>';
            cnt.appendChild(desc);
            
            for(subtype of types.subtypes){
                //Agregar las cuentas según los sub-tipos
                var accounts = currency.accounts;
                for(acc of accounts){
                    var subt = document.createElement("input"); 
                    subt.classList.add("currencyInpt");
                    subt.value = acc.dsc;//acc.subtype.dsc;
                    subt.setAttribute("accid",acc.id);
                    //Cuando se actualiza el campo se dispara el guardar
                    subt.addEventListener("change",function(){
                        if(priv){
                            saveAccount(this.getAttribute("accid"),this.value); 
                        }else{
                            var msg = document.getElementById("messageError");
                            msg.innerHTML= "No posee privilegios para modificar cuentas contables";
                            msg.classList.add("msgError"); 
                            msg.style.display="block";
                            setTimeout(function() {
                                msg.classList.remove("msgError");   
                                msg.style.display="none";
                                entryLevel();
                            }, 3000);
                        }
                    });
                    if(acc.subtype.id == subtype.id)
                        cnt.appendChild(subt);
                }
                    
            }
            
            columnCurr.appendChild(cnt);
        }
        
            i++;
        document.getElementById("overflowXPair").appendChild(columnCurr);
    }
    
}
/*Guardar la cuenta*/
function saveAccount(id,dsc){
var par = {};
    par.id = id;
    par.account = dsc;
    par.sessionid = sessionId;
    callWS("POST", "accounting/update", par, rspSaveAcc);
    return 0;
}
function rspSaveAcc(status,rsp){
    var resp = JSON.parse(rsp);
    switch(status){
        case 200:
            entryLevel();//Se cargan las cuentas de nuevo
            break;
        default:
            var msg = document.getElementById("messageError");
            msg.innerHTML= resp.msg;
            msg.classList.add("msgError"); 
            msg.style.display="block";
            setTimeout(function() {
                msg.classList.remove("msgError"); 
                msg.innerHTML = "";
                msg.style.display="none";
                entryLevel();
            }, 3000);
        break;
    }
}
