const nome = document.getElementById("nome");
const email = document.getElementById("email");
const genero = document.getElementById("genero");
const idTipoUsuario = document.getElementById("idTipoUsuario");
const nomeUsuario = document.getElementById("nomeUsuario");
const bi = document.getElementById("bi");
const btn = window.parent.document.getElementById("btn-submit");
console.log("Cheguei!");

let numberRegExp = new RegExp('^[0-9-() ]+$');
let letterRegExp = new RegExp('^[a-zA-Z ]+$');
let biRegExp = new RegExp('^[a-zA-Z0-9]+$');
let emailRegExp = new RegExp('^[A-Za-z0-9._-]{3,}@[A-Za-z._-]{3,}[.]{1}[A-Za-z._-]{2,6}$');
//document.querySelector("#idClasse").classList.add("is-invalidoooooo");

console.log('Pegar os smalls: ', document.querySelector('.form-group small'));

function nomeWarning(small){
	nome.className = "form-control is-warning";
	small.style.visibility = "visible";
	small.style.color = "#ffc107";
	small.innerText = "Campo Nome Completo é obrigatório!";
	btn.setAttribute('disabled', 'disabled');
}

function nomeValid(small){
	nome.className = "form-control is-valid";
	btn.removeAttribute('disabled');
	small.style.visibility = "hidden";
}

nome.addEventListener("keyup", function(){
	let small = nome.parentElement.querySelectorAll("small")[1];
	if(nome.value === ''){
		nomeWarning(small);
	} else {
		nomeValid(small);
	}
});

function idTipoUsuarioInvalid(small){
	idTipoUsuario.classList.add("select2-danger");
	idTipoUsuario.setAttribute('data-dropdown-css-class', 'select2-danger');
	small.style.visibility = "visible";
	small.style.color = "#dc3545";
	small.innerText = "Selecione um tipo de usuário!";
	btn.setAttribute('disabled', 'disabled');
}

function idTipoUsuarioValid(small){
	idTipoUsuario.classList.remove("select2-danger");
	idTipoUsuario.classList.add("is-valid");
	idTipoUsuario.style.borderColor = "#ffc107";
	btn.removeAttribute('disabled');
	small.style.visibility = "hidden";
}

$('#idTipoUsuario').select2().on('change', function(){
    let small = idTipoUsuario.parentElement.querySelectorAll("small")[1];
    console.log($("#idTipoUsuario").val());
    if($("#idTipoUsuario").val() == 0){
		idTipoUsuarioInvalid(small);
    } else {
		idTipoUsuarioValid(small);
    }
});

function generoInvalid(small){
	genero.classList.add("select2-danger");
	genero.setAttribute('data-dropdown-css-class', 'select2-danger');
	small.style.visibility = "visible";
	small.style.color = "#dc3545";
	small.innerText = "Selecione um Género!";
	btn.setAttribute('disabled', 'disabled');
}

function generoValid(small){
	genero.classList.remove("select2-danger");
	genero.classList.add("is-valid");
	genero.style.borderColor = "#ffc107";
	btn.removeAttribute('disabled');
	small.style.visibility = "hidden";
}

$('#genero').select2().on('change', function(){
    let small = genero.parentElement.querySelectorAll("small")[1];
    console.log($("#genero").val());
    if($("#genero").val() == 0){
		generoInvalid(small);
    } else {
		generoValid(small);
    }
});

function biWarning(small){
	bi.className = "form-control is-warning";
	small.style.visibility = "visible";
	small.style.color = "#ffc107";
	small.innerText = "Campo Bilhete de Identidade é obrigatório!";
	btn.setAttribute('disabled', 'disabled');
}

function biValid(small){
	bi.className = "form-control is-valid";
	btn.removeAttribute('disabled');
	small.style.visibility = "hidden";
}

bi.addEventListener("keyup", function(){
	let small = bi.parentElement.querySelectorAll("small")[1];
	if(bi.value === ''){
		biWarning(small);
	} else {
		if(biRegExp.test(bi.value)){
			biValid(small);
		}
	}
});

function emailInvalidExist(small){
	email.className = "form-control is-invalid";
	small.style.visibility = "visible";
	small.style.color = "#dc3545";
	small.innerText = "E-mail já existe. Digite outro!";
	btn.setAttribute('disabled', 'disabled');
}

function emailNormal(small){
	email.className = "form-control";
	small.style.visibility = "hidden";
	small.style.color = "#dc3545";
	btn.removeAttribute('disabled');
}

function emailWarning(small){
	email.className = "form-control is-warning";
	small.style.visibility = "visible";
	small.style.color = "#ffc107";
	small.innerText = "Campo E-mail é obrigatório!";
	btn.setAttribute('disabled', 'disabled');
}

function emailInvalid(small){
	email.className = "form-control is-invalid";
	small.style.visibility = "visible";
	small.style.color = "#dc3545";
	small.innerText = "E-mail inválido. Digite um e-mail válido!";
	btn.setAttribute('disabled', 'disabled');
}

function emailValid(small){
	console.log("É igual a zero!");
	email.className = "form-control is-valid";
	small.style.visibility = "hidden";
	btn.removeAttribute('disabled');
}

function queryEmail(){
	$(document).on("keyup", "#email", function(e){
		e.preventDefault();
		var email = $(this).val();
		$.ajax({
		  url: "includes/read/verifyEmail.inc.php",
		  type: "post",
		  dataType: "json",
		  data: {
			email: email
		  }
		  }).done(function(data){
			let email = document.getElementById("email");
			let small = email.parentElement.querySelectorAll("small")[1];
			//$("#example1").DataTable().destroy();
			console.log("Estes são os e-mails: ", data[0]['contador']);
			if(data[0]['contador'] > 0){
			  console.log("É diferente de zero!");
			  if(email.value !== ""){
				emailInvalidExist(small);
			  } else {
				emailNormal(small);
			  }
			} else {
				if(email.value === ''){
					emailWarning(small);
				} else if(!emailRegExp.test(email.value)){
					emailInvalid(small);
				} else {
					emailValid(small);
				}
			}
		});
	});
}

queryEmail();

function nomeUsuarioInvalidExist(small){
	console.log("É diferente de zero!");
	nomeUsuario.className = "form-control is-invalid";
	small.style.visibility = "visible";
	small.style.color = "#dc3545";
	small.innerText = "Nome de usuário já existe. Digite outro!";
	btn.setAttribute('disabled', 'disabled');
}

function nomeUsuarioWarning(small){
	nomeUsuario.className = "form-control is-warning";
	small.style.visibility = "visible";
	small.style.color = "#ffc107";
	small.innerText = "Campo nome usuário é um campo obrigatório!";
	btn.setAttribute('disabled', 'disabled');
}

function nomeUsuarioValid(small){
	console.log("É igual a zero!");
	nomeUsuario.className = "form-control is-valid";
	small.style.visibility = "hidden";
	btn.removeAttribute('disabled');
}

function queryNomeUsuario(){
	$(document).on("keyup", "#nomeUsuario", function(e){
		e.preventDefault();
		var nomeUsuario = $(this).val();
		$.ajax({
		  url: "includes/read/verifyNomeUsuario.inc.php",
		  type: "post",
		  dataType: "json",
		  data: {
			nomeUsuario: nomeUsuario
		  }
		  }).done(function(data){
			let nomeUsuario = document.getElementById("nomeUsuario");
			let small = nomeUsuario.parentElement.querySelectorAll("small")[1];
			//$("#example1").DataTable().destroy();
			console.log("Estes são os nomeUsuario-s: ", data[0]['contador']);
			if(data[0]['contador'] > 0){
				nomeUsuarioInvalidExist(small);
			} else {
				if(nomeUsuario.value === ''){
					nomeUsuarioWarning(small);
				} else {
					nomeUsuarioValid(small);
				}
			}
		});
	});
}

queryNomeUsuario();

btn.addEventListener("click", function(){
	let smallNome = nome.parentElement.querySelectorAll("small")[1];
	let smallIdTipoUsuario = idTipoUsuario.parentElement.querySelectorAll("small")[1];
	let smallGenero = genero.parentElement.querySelectorAll("small")[1];
	let smallBi = bi.parentElement.querySelectorAll("small")[1];
	let smallEmail = email.parentElement.querySelectorAll("small")[1];
	let smallNomeUsuario = nomeUsuario.parentElement.querySelectorAll("small")[1];
	if(nome.value == ''){
        nomeWarning(smallNome);
    } else {
		nomeValid(smallNome);
	}
	
	if($("#idTipoUsuario").val() == 0){
        idTipoUsuarioInvalid(smallIdTipoUsuario);
    }else {
		idTipoUsuarioValid(smallIdTipoUsuario);
	} 

	if($("#genero").val() == 0){
        generoInvalid(smallGenero);
    }else {
		generoValid(smallGenero);
	} 

	if(nomeUsuario.value == ''){
		nomeUsuarioWarning(smallNomeUsuario);
	} else {
		queryNomeUsuario();
	}

	if(bi.value == ''){
        biWarning(smallBi);
    } else {
		biValid(smallBi);
	}

	if(email.value == ''){
		emailWarning(smallEmail);
	} else {
		queryEmail();
	}
});