var type = "add";
$(document).ready(function() {
    
    const validation  = new JustValidate('#form',{
        errorFieldCssClass: 'is-invalid',
    });
    validation
    // .addField('#username', [
    //     {
    //         rule: 'required',
    //     },
    //     {
    //         rule: 'minLength',
    //         value: 3,
    //     },
    //     {
    //         rule: 'maxLength',
    //         value: 30,
    //     },
    // ])
    // .addField('#firstName', [
    //     {
    //         rule: 'required',
    //     },
    // ])
    // .addField('#lastName', [
    //     {
    //         rule: 'required',
    //     },
    // ])
    // .addField('#email', [
    //     {
    //         rule: 'required',
    //     },
    //     {
    //         rule: 'email',
    //         errorMessage: 'Email is invalid!',
    //     },
    // ])
    .addField('#password', [
        {
            rule: 'required',
        },
        {
            rule: 'strongPassword',
        },
    ])
    // .addField('#phone', [
    //     {
    //         rule: 'required',
    //     },{
    //         rule: 'number',
    //     },
    // ])
    .onSuccess((event)=>{
        $("#togglePassword").css("top","28%")
        $("#hidetogglePassword").css("top","28%")
        submitEditForm()
    }).onFail(()=> {
       
        // if($)
        $("#togglePassword").css("top","10%")
        $("#hidetogglePassword").css("top","10%")
    })
    loadUserProfile();
    $("#password").keyup(()=> {
        let data = $(".just-validate-error-label").text().length
        if(data > 21){
            $("#togglePassword").css("top","10%")
            $("#hidetogglePassword").css("top","10%")
        }
        else if(data == 21) {
            $("#togglePassword").css("top","20%")
            $("#hidetogglePassword").css("top","20%")
        }
        else {
            $("#togglePassword").css("top","28%")
            $("#hidetogglePassword").css("top","28%")
        }
        console.log(data)
    })
})
function loadUserProfile(){
    let id = JSON.parse(sessionStorage.getItem("sessionData"))
     $.ajax({
        type: "get",
        url: "../cgi/cgi_Account.py",
        contentType: 'application/json',
        dataType:  'json',
        headers: { 'Access-Control-Allow-Origin': '*' },
        data: {requestType : "getUserDetails",id : id.Userid},
        success: function (response) {
            $("#form").removeClass("d-none")
            $("#graph-water-mark").addClass("d-none");
            $("#email").prop("disabled", true );
            $("#username").prop("disabled", true );
            $("#username").val(response[0].username);
            $("#firstName").val(response[0].firstname);
            $("#lastName").val(response[0].lastname);
            $("#email").val(response[0].email);
            $("#password").val(response[0].password);
            $("#phone").val(response[0].phone);
            let type = $("#password");
        	let typeValue = response[0].password_hidden == "Yes" ? "password" : "text";
			type.attr("type",typeValue);
			if(response[0].password_hidden == 'Yes'){
				$("#togglePassword").show() 
            	$("#hidetogglePassword").hide()
			}
			else{
				$("#togglePassword").hide() 
            	$("#hidetogglePassword").show()
			}
        },
        error: function (ex) {
        }
    });
  
}
function callPythonCgi(request){
    $.ajax({
        type: request.method,
        url: request.url,
        contentType: 'application/json',
        dataType:  'json',
        headers: { 'Access-Control-Allow-Origin': '*' },
        data: request.parameters,
        success: function (response) {
           if(request.type == 'saveUser'){
                if(response.status == 'success'){
                    mymodal.find('.modal-title').text('Success');
                    mymodal.find('.modal-body').text(response.description);
                }
                else {
                    mymodal.find('.modal-title').text('Error');
                    mymodal.find('.modal-body').text(response.description);
                }
                mymodal.modal('show');
                setTimeout(()=> {
                    mymodal.modal("hide")
                },autoClose)
            }
        },
        error: function (ex) {
        }
    });
}

function submitEditForm() {
    var data = $('#form').serializeArray().reduce(function(obj, item) {
        obj[item.name] = item.value;
        return obj;
    }, {});
    let id = JSON.parse(sessionStorage.getItem("sessionData"))
    var request = new Request()
    request.method = 'get';
    request.url = "../cgi/cgi_Account.py";
    request.parameters = {id:id.Userid,firstName:data.firstName,lastName:data.lastName, password:data.password, phone:data.phone,requestType : "updateUser"};
    request.type = "saveUser";
    callPythonCgi(request);
}

$(".togglePassword").click(function(){
    let type = $("#password");
    let typeValue = type.attr("type") === "password" ? "text" : "password";
    // console.log(typeValue);
    if(typeValue == "password" ){
        $("#togglePassword").show() 
        $("#hidetogglePassword").hide() 
    }
    else {
        $("#togglePassword").hide() 
        $("#hidetogglePassword").show() 
    }
    type.attr("type",typeValue);
    let id = JSON.parse(sessionStorage.getItem("sessionData"))
    parameters = {
        hidden : typeValue == "password" ? "Yes" : "No",
        requestType: "password_hidden",
        id : id.Userid
    }
    $.ajax({
        type: "get",
        url: "../cgi/cgi_Account.py",
        contentType: 'application/json',
        dataType: 'json',
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        data: parameters,
        success: function (response) {
        },
        error: function (ex) {
            isCllicked = false;
            $('#test').html(ex.responseText);
        }
    });
})