const userField = document.getElementById("username");
const passwordField = document.getElementById("password");
const remindus = document.getElementById("remindus");
const loginButton = document.getElementById("loginButton");
const info = document.getElementById("info");



userField.addEventListener("keyup", (event) => {
  if (event.key === "Enter") {
    passwordField.value = null;
    passwordField.focus()
  }
});


passwordField.addEventListener("keyup", (event) => {
  if (event.key === "Enter") {
     login()
  }
});

function login() {
    info.innerHTML = ""
    const userValue = userField.value;
    const passwordValue = passwordField.value;

    if(userValue == "" | passwordValue == "") {
        info.innerHTML = "Tous les champs doivent être remplis."

    } else if(userValue.includes(" ")) {

        info.innerHTML = "Le nom d'utilisateur ne peut pas contenir un espace"
    } else {



        const loginData = {
            "username":userValue,
            "password": passwordValue,
            "remindus": remindus.checked
        }


        fetch('/login', {
            method: 'POST',
            redirect: 'follow',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(loginData)
        })
        .then(response => response.json())
        .then(response => redirect(response))

        function redirect(response) {

            if(response.token == "auth_failed") {
                passwordField.value = null;
                info.innerHTML = "Le nom d'utilisateur ou le mot de passe est éronné"

            } else if(response.token == "auth_success") {
                
                window.location.href = "/"

            }

           

        } 
    }

}

loginButton.addEventListener("click", () => {

    login()

   
});
