var validStudents = {};
var grades = [];
var section = [];
var studentsPerSection = [];
var id;
var totally = 0;
var studentCi = [];
var registerEnabled = 1;
var isPrivat;

function registerStudents(){
    
    var student = [];
    var inputText;
    var error = document.getElementById('error');
    let buttonCharge = document.getElementsByClassName("chargePupils")[0];
    
    loadScreen()
    buttonCharge.setAttribute('disabled','');
    buttonCharge.style.opacity= 0.5;
    
    inputText = document.getElementsByClassName('namePupil');
    information = {
      name: document.getElementsByClassName('namePupil'),
      lastName: document.getElementsByClassName('lastPupil'),
      gender: document.getElementsByClassName('genderSelect'),
      birthDate: document.getElementsByClassName('birth'),
      ci: document.getElementsByClassName('ci'),
      grade: document.getElementsByClassName('gradeSelect'),
      section: document.getElementsByClassName('sectionSelect'),
    };
    
    for(let i = 0; i < inputText.length; i++){
        
        if( i === 0){
            student['name'] = information.name[i].value;
            student['lastName'] = information.lastName[i].value;
            student['gender'] = information.gender[i].value;
            student['birthDate'] = information.birthDate[i].value;
            student['ci'] = information.ci[i].value;
            student['grade'] = information.grade[i].value;
            student['section'] = information.section[i].value;
        }else{
            student['name'] += "~" + information.name[i].value;
            student['lastName'] += "~" + information.lastName[i].value;
            student['gender'] += "~" + information.gender[i].value;
            student['birthDate'] += "," + information.birthDate[i].value;
            student['ci'] += "~" + information.ci[i].value;
            student['grade'] += "~" + information.grade[i].value;
            student['section'] += "~" + information.section[i].value;
        }
    }
    
    var params = {
        name: student['name'],
        surname: student['lastName'],
        gender: student['gender'],
        birthdate: student['birthDate'],
        ci: student['ci'],
        level: student['grade'],
        section: student['section'],
        sessionid: getSessionId(),
        schoolid: id,
        id: 0,
    }
    
    if(inputText.length === 0){
        error.innerHTML = "Ning\u00FAn alumno ingresado";
        closeLoad();
        buttonCharge.style.opacity= 1;
        buttonCharge.removeAttribute('disabled','');
    }else{
        error.innerHTML = "";
        callWS("POST", "pupils/update", params, respx);
    }
    
    function respx(status, respText){
        console.log(JSON.parse(respText));
        var json = JSON.parse(respText);
        if (status == 200){
            let timerVal = 0;
            
            let timer = setInterval(function(){
                timerVal++;
                if(timerVal == 2){
                    closeLoad();
                    document.getElementById('confirmation').innerHTML = "Registro de alumnos Exitoso";
                }
                
                if(timerVal == 3){
                    clearInterval(timer);
                    navigationMenu('searchStudent');
                }
            },1500);
            
            disabledEstimatedBtn()
        }else if( status == 404){
            error.innerHTML = "No se pudo modificar";
        }
    }
}

function gotoTop(){
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
}
    
window.onload = function carga() {
    
    getRegisterEnabled();
    
    clearQtyPupils();
    var params = {
        ssid: getSessionId(),
    };
    
    //Logout
    document.getElementById('logOut').addEventListener("click", function(){
        gotoPage('login','main',{});
    });
    
    
    let dateNow = document.getElementById('birthDay');
    let date = new Date();
    date = date.getMonth();
    dateNow.max = new Date().toISOString().split("T")[0];
    loadScreen();
    callWS("GET", "schools/entry", params, respx);
    
    function respx(status, respText){
        console.log(JSON.parse(respText));
        var json = JSON.parse(respText);
        if (status == 200){
            
            showLabelPrivate(json.privat);
            
            isPrivat = json.privat;
            
            json.editlocked ? disabledButton() : changeButtonLink();
            json.privat ? null : document.getElementById("estimatedLink").innerHTML = "Estimaci\u00F3n";
            document.getElementsByClassName('userName')[0].innerHTML = json.contact;
            document.getElementById('schoolName').innerHTML = json.name;
            id = json.id;
            validStudents = json.estimatedpupils;
            grades = Object.keys(validStudents);
        
        
            for(let i = 0; i < grades.length; i++){
                studentsPerSection[grades[i]] = Object.values(validStudents[grades[i]]);
            }
        
             for(let i = 0; i < Object.keys(studentsPerSection).length ; i++){
                    for(let j = 0; j < studentsPerSection[grades[0]].length; j++){
                        if (studentsPerSection[grades[i]][j] != undefined && studentsPerSection[grades[i]][j] != null) {
                            totally += parseInt(studentsPerSection[grades[i]][j]);
                        }
                    }
                }
        
            document.getElementsByClassName('estimatedPupilsTxt')[0].innerHTML = `Cupos estimados: ${totally}`;
        
            var paramsList = {
                sessionid: getSessionId(),
                schoolid: json.id,
                filter: ``,
                offset: 0,
                order: `id ASC`,
                numofrecords: totally,
            };
        
            callWS("GET", "pupils/list", paramsList, respxList);
            }
        closeLoad();
    }
}

function disabledButton(){
    document.getElementsByClassName('registerStudents')[0].style.opacity = 0.5;
    document.getElementById('studentLink').style.cursor = "default";
    document.getElementById('studentLink').setAttribute('href','javascript:void(0)');
    
    document.getElementById('linkPupils').style.opacity = 0.5;
    document.getElementById('linkPupils').style.cursor = "default";
    document.getElementById('linkPupils').setAttribute('href','javascript:void(0)');
}

function changeButtonLink(){
    var link = document.getElementById('studentLink');
    link.setAttribute('href',`javascript:navigationMenu('searchStudent')`);
}

function respxList(status, respText){
    console.log(JSON.parse(respText));
    var json = JSON.parse(respText);
    
    if (status == 200){
        document.getElementsByClassName('pupilsReg')[0].innerHTML = `Alumnos registrados: ${json.numofrecords}`;
        if(json.records != null){
            for(let i = 0; i < json.records.length ; i++){
                if(json.records[i].id !== null){
                    totally--;
                    studentCi[i] = json.records[i].ci;
                }
            }
        }
        
    }
    
    if(isPrivat){
        document.getElementsByClassName('pupilsAval')[0].innerHTML = `Cupos disponibles: ${totally}`;
    }
    
}

function makeRegister() {
    var error = document.getElementById('error');
    var valId=/^(([0-9])|(ext|x)){1,11}$/;
    
    var student = {
      name: document.getElementById('namePupil').value,
      lastName: document.getElementById('lastName').value,
      gender: document.getElementById('gender').value,
      birthDate: document.getElementById('birthDay').value,
      ci: document.getElementById('id').value,
      grade: document.getElementById('grade').value,
      section: document.getElementById('section').value,
    };
    
    var inputText = document.getElementsByClassName('namePupil').length;
    
    let today = new Date();
    let validDate = new Date(student.birthDate);
    
    if( student.name == "" || student.lastName == "" || student.gender != "M" && student.gender != "F" || student.birthDate == "" || student.grade == "" || student.section == ""){
        error.innerHTML = "Campos Vac\u00EDos";
    }else if(validDate.getFullYear() > today.getFullYear() || validDate.getFullYear() < 2004){
        error.innerHTML = "Fecha de Nacimiento incorrecta";
    }else if(!valId.test(student.ci) && student.ci != "" || (student.ci > 99999999999 && student.ci != "")){
        error.innerHTML = "Identificaci\u00F3n incorrecta";
    }else if(validateCi(student.ci)){
        error.innerHTML = "Esta c\u00E9dula ya fue ingresada";
    }else if(evaluateStudent()){
        error.innerHTML = "Excedi\u00F3 el n\u00FAmero de alumnos estimados";
    }else{
        studentCi[studentCi.length] = student.ci;
        error.innerHTML = "";
        var table = document.getElementsByClassName('tableForm')[0].insertRow(2).innerHTML = `
    <td>
        <input type="text" class="namePupil" value="${student.name}" readonly>
    </td>
    <td>
        <input type="text" class="lastPupil" value="${student.lastName}" readonly>
    </td>
    <td>
        <select class="genderSelect"  readonly disabled>
            <option value="${student.gender}" selected>${student.gender == "M" ? "Masculino" : "Femenino"}</option>
        </select>
    </td>
    <td>
        <input type="date" class="birth" value="${student.birthDate}" readonly>
    </td>
    <td>
        <input type="text" class="ci" value="${student.ci}" readonly>
    </td>
    <td>
        <select class="gradeSelect" readonly disabled>
            <option value="${student.grade}" selected>${student.grade}</option>
        </select>
    </td>
    <td>
        <select class="sectionSelect" readonly disabled>
            <option value="${student.section}" selected>${student.section}</option>
        </select>
    </td>
    <td>
        <span class="lessCircle" onclick="deleteRow(this)"></span>
    </td>`;
    
    document.getElementById('namePupil').value = "";
    document.getElementById('lastName').value = "";
    document.getElementById('gender').value = "";
    document.getElementById('birthDay').value = "";
    document.getElementById('id').value = "";
    document.getElementById('grade').value = "";
    document.getElementById('section').value = "";
    }
}

function deleteRow(e){
  var table = document.getElementsByClassName("tableForm")[0];
  var rowCount = table.rows.length;
  
  totally++;
  if(isPrivat){
      document.getElementsByClassName('pupilsAval')[0].innerHTML = `Cupos disponibles: ${totally}`;
  }
  

  if(rowCount <= 2)
    alert('No se puede eliminar el encabezado');
  else
    e.closest('tr').remove();
}

function evaluateStudent(){
    
    if(isPrivat){
        
            
        if(totally <= 0){
            
            return true;
        }else{
            totally--;
            document.getElementsByClassName('pupilsAval')[0].innerHTML = `Cupos disponibles: ${totally}`;
            return false;
        }
    }else{
        return false;
    }
}


function validateCi(id){
    if(id == ""){
        return false;
    }else{
        for(let i = 0; i < studentCi.length ; i++){
            if(id == studentCi[i]){
                return true;
            }
        }
        return false;
    }
    
}

function loadScreen() {
    var popup = document.getElementsByClassName("popupLoad")[0];
    
    var style = document.createElement('style');
    document.head.appendChild(style);
    gotoTop();
    style.sheet.insertRule(`.popupLoad {position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: ${window.screen.height <= 635 ? "auto" : '100%'};
        background-color: rgba(0,0,0,0.5); display:flex; align-items: center;
        ${window.screen.height <= 635 ? 'padding: 10px 0px;' : null}}`);
    
    document.body.style.overflowY = window.screen.height <= 635 ? "scroll" : "hidden";
        
    popup.innerHTML = `
    <div class="loaded">
        <div class="loaderWrapper">
            <div class="loader"></div>
        </div>
    </div>`;
}

function closeLoad() {
    var popup = document.getElementsByClassName("popupLoad")[0];
    var style = document.createElement('style');
    document.head.appendChild(style);
    
    style.sheet.insertRule(`.popupLoad {display: none}`);
        document.body.style.overflowY = "scroll";
}

function getRegisterEnabled(){
    let params = {
        id: 7
    }
    loadScreen();
    callWS("GET", "settings/entryregister", params, respx);
    
    //Obtenemos los datos del servicio
    function respx(status, respText){
        var json = JSON.parse(respText);
        closeLoad();
        if (status == 200){
            registerEnabled = parseInt(json.entry.content);
            
            if(registerEnabled == 0){
                gotoPage('home','searchStudent',{});
            }
        }else{
            console.log(json.msg);
        }
    }
}

function disabledEstimatedBtn () {
    let params = {
        id: 7
    }
    loadScreen();
    callWS("GET", "settings/entryregister", params, respx);
    
    //Obtenemos los datos del servicio
    function respx(status, respText){
        var json = JSON.parse(respText);
        closeLoad();
        if (status == 200){
            if (json.entry.content == 0) {
                showLabelPrivate(true);
            }
        }else{
            console.log(json.msg);
        }
    }
}