const code = 10;
console.log("js profile");


$("#btnEdit").on("click", function(e){
    e.preventDefault()
    
    if(validateUsername() == false){
        alert("format username salah!")
    } else if(validateEmail() == false){
        alert("Format email salah")
    } else if(validateName() == false){
        alert("Format nama Salah")
    } else if(isUsernameExist() == true){
        alert("username sudah terpakai")
    } else if(isEmailExist()){
        alert("Email Sudah Terpakai")
    } else {
        editProfile()
    }
})

$("#btnPas").on("click", function(e){
    var tblUserPassword = loadPassword();
    editPassword(tblUserPassword);
})

function editProfile(){
    $username   = $("#usernameUP").val();
    $name       = $("#nameUP").val();
    $email      = $("#emailUP").val();
    $id         = $("#id_userUP").val();

    console.log($username)

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/api/updateProfile',
        data: {
            id          : $id,
            username    : $username,
            email       : $email,
            name        : $name,
        },
        success: function(result){
           alert("success")
           location.reload();
           //document.getElementById("nameUP").value = name;

        },
        error: function(xhr){
            alert(xhr.status+'-'+xhr.statusText);
        }
    });
}

//isUsernameExist();
userProfileData()
function userProfileData(){
    let iduser = idUserProfile;
    console.log(iduser);
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/api/loadusername',
        async: false,
        data: {
            id      : iduser,
        },
        success: function(result){
            
            var data = result.data;
            console.log(data[0].username);
            
            document.getElementById("usernameProfile").innerHTML    = data[0].username;
            document.getElementById("nameProfile").innerHTML        = data[0].name;
            document.getElementById("emailProfile").innerHTML       = data[0].email;

            document.getElementById("usernameUP").value             = data[0].username;
            document.getElementById("nameUP").value                 = data[0].name;
            document.getElementById("emailUP").value                = data[0].email;
            
        },
        error: function(xhr){
            alert(xhr.status+'-'+xhr.statusText);
        }
    });
    
}

function userDataCounter(){

}

function validateName(){
    var validName   = /^[a-zA-Z ]+$/;
    var name        = document.getElementById("nameUP").value;

    return validName.test(name);
}

function validateEmail(){
    var validEmail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    var email = document.getElementById("emailUP").value;
    //console.log(validEmail.test(email));

    return validEmail.test(email);  
}

function isUsernameExist(){
    var exist           = false;
    
    var currentUsername = document.getElementById("usernameProfile").innerHTML; 
    var username        = document.getElementById("usernameUP").value;
    
    console.log(currentUsername);
    console.log(username);
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/api/loadusername',
        async: false,
        data: {
            id  : null,
        },
        success: function(result){
            //console.log(result.data);
            //let counterExist    = 0;
            var data = result.data;
            let i = 0;
            for(i; i<data.length; i++){
                if(username === data[i].username){
                    //exist = true;
                    //counterExist += 1;
                    
                    if (username == currentUsername){
                        exist = false;
                    } else{
                        exist = true;
                    }
                }
                
            }
            
        },
        error: function(xhr){
            //alert(xhr.status+'-'+xhr.statusText);
        }
    });
    console.log(exist);
    return exist;
}

function isEmailExist(){
    var exist           = false;
    
    var currentEmail = document.getElementById("emailProfile").innerHTML; 
    var email        = document.getElementById("emailUP").value;
    
    // console.log(currentUsername);
    // console.log(username);
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/api/loadusername',
        async: false,
        data: {
            id  : null,
        },
        success: function(result){
            //console.log(result.data);
            //let counterExist    = 0;
            var data = result.data;
            let i = 0;
            for(i; i<data.length; i++){
                if(email === data[i].email){
                    //exist = true;
                    //counterExist += 1;
                    
                    if (email == currentEmail){
                        exist = false;
                    } else{
                        exist = true;
                    }
                }
                
            }
            
        },
        error: function(xhr){
            //alert(xhr.status+'-'+xhr.statusText);
        }
    });
    console.log(exist);
    return exist;
}

function validateUsername(){
    var validUsername = /^[a-z0-9_]{3,16}$/;
    var username      = document.getElementById("usernameUP").value;

    return validUsername.test(username);
}

//var tblUserPassword = loadPassword();
// console.log(tblUserPassword);
function loadPassword(){
    let $id             =   idUserProfile;
    let curdbPas        = null;
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/api/loadusername',
        async: false,
        data: {
            id  : $id,
        },
        success: function(result){
            //console.log(result.data);
            //let counterExist    = 0;
            var data = result.data;
            //console.log(data[0].password);
            curdbPas = data[0].password;
        },
        error: function(xhr){
            //alert(xhr.status+'-'+xhr.statusText);
        }
    });

    return curdbPas;
}

function editPassword(pass){
    let $id             =   $("#id_userPas").val();
    let currentPassword =   document.getElementById("currentPas").value;
    let newPassword     =   document.getElementById("newPas").value;
    let confirmPassword =   document.getElementById("confPas").value;
    let passValidator   =   pass;

    console.log(currentPassword);
    console.log(newPassword);
    console.log(confirmPassword);
    console.log(passValidator);

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/api/updatePassword',
        data: {
            id              : $id,
            currentPas      : currentPassword,
            newPas          : newPassword,
            confirmPassword : confirmPassword,
            passDB          : passValidator,
            code            : code,
        },
        success: function(result){
           alert(result.info);
           location.reload();  
        },
        error: function(xhr){
            alert(xhr.status+'-'+xhr.statusText);
        }
    });
    
}