
document.addEventListener("DOMContentLoaded", _ => 
{
    // check if the userData is logged in and if so load the editor
    fetch("/api/user/isLoggedIn").then(res => 
    {
        if (res.ok)
        {
            window.location.href = "./editor.html";
        }
    });
});

/**
 * Shows respective error message for form
 * @param {string} message The error message to show
 * @param {string} form The form to show the error message for
 */
function showErrorMessage(message, form) 
{
    document.querySelector(`#${form}Error`).classList.remove("hidden");
    document.querySelector(`#${form}Error div`).innerText = message;
}


/**
 * Switches between the different forms
 * @param {string} from The css selector of form to switch from
 * @param {string} to The css selector of form to switch to
 */
function switchView(from, to)
{
    document.querySelector(from).classList.toggle("shown");
    setTimeout(() => document.querySelector(from).style.transform = "translateX(150vw)", 500);
    setTimeout(() => document.querySelector(from).style.display = "none", 500);
    setTimeout(() => document.querySelector(to).style.removeProperty("display"), 200);
    setTimeout(() => document.querySelector(to).classList.toggle("shown"), 300);
    setTimeout(() => document.querySelector(to).style.removeProperty("transform"), 400);
}

document.querySelector("#login form").addEventListener("submit", e => 
{
    e.preventDefault();
    let loginData = new FormData();
    if (e.target.username.value.length > 0 && e.target.password.value.length > 0)
    {
        loginData.append("username", e.target.username.value);
        loginData.append("password", e.target.password.value);
        fetch("/api/user/login", 
    {
            method: "POST", 
            body: loginData
        }).then(res => res.json().then(json =>
        {
            if (res.ok)
            {
                localStorage.setItem("token", json.token);
                window.location.href = "./editor.html";
                return;
            }
            if (res.status === 400)
            {
                showErrorMessage("Please type in a username and password.", "login");
                return;
            }
            showErrorMessage("Invalid username or password.", "login");
        }));
       return; 
    }
    showErrorMessage("Please type in a username and password.", "login");
});

document.querySelector("#loginError .close").addEventListener("click", () =>
    document.querySelector("#loginError").classList.toggle("hidden"));

document.querySelector("#resetError .close").addEventListener("click", () =>
    document.querySelector("#resetError").classList.toggle("hidden"));

document.querySelector("#changeError .close").addEventListener("click", () =>
    document.querySelector("#changeError").classList.toggle("hidden"));


document.querySelectorAll("form i.fa-eye").forEach(i => 
{
    i.addEventListener("click", e => 
    {
        if (e.target.previousElementSibling.type === "password")
        {
            e.target.previousElementSibling.type = "text";
            e.target.classList.remove("fa-eye");
            e.target.classList.add("fa-eye-slash");
            return;
        }
        e.target.previousElementSibling.type = "password";
        e.target.classList.remove("fa-eye-slash");
        e.target.classList.add("fa-eye");
    }); 
});

// showing and hiding different forms

document.querySelector("#resetPwd").addEventListener("click", () =>
{
    switchView("#login", "#resetPassword");
});

document.querySelector("#loginBtn").addEventListener("click", () =>
{
    switchView("#resetPassword", "#login");
});

document.querySelector("#resetPassword form").addEventListener("submit", e =>
{
    e.preventDefault();
    let resetData = new FormData();
    if (e.target.email === "")
    {
       showErrorMessage("Please type in your email.", "reset");
       return;
    }
    window.email = e.target.email.value;
    resetData.append("email", e.target.email.value);
    fetch(`/api/user/checkResetEmail/${e.target.email.value}`).then(res =>
    {
        if (res.ok)
        {
            // show check code form 
            switchView("#resetPassword", "#checkResetCode");
        }
        showErrorMessage("Invalid email.", "reset");
    });
});

document.querySelector("#checkResetCode form").addEventListener("submit", e =>
{
    e.preventDefault();
    let resetCode = new FormData();
    if (e.target.code.value === "")
    {
        showErrorMessage("Please type in your reset code.", "check");
        return;
    }
    resetCode.append("code", e.target.code.value);
    fetch(`/api/user/checkResetCode/${e.target.code.value}`).then(res =>
    {
        if (res.ok)
        {
            // show reset password form
            switchView("#checkResetCode", "#changePassword");
        }
        showErrorMessage("Invalid code.", "resetCode");
    });
});

document.querySelector("#changePassword form").addEventListener("submit", e =>
{
    e.preventDefault();
    let resetPassword = new FormData();
    if (e.target.pass.value === "" && e.target.rePass.value === "")
    {
        showErrorMessage("Please type in a new password.", "change");
        return;
    }
    
    if (e.target.pass.value !== e.target.rePass.value)
    {
        showErrorMessage("Passwords do not match.", "change");
        return;
    }
    
    resetPassword.append("password", e.target.pass.value);
    fetch(`/api/user/changePassword`, 
    {
        method: "POST",
        body: resetPassword
    }).then(res =>
    {
        if (res.ok)
        {
            // show login form
            switchView("#changePassword", "#login");
        }
        showErrorMessage("Something went wrong.", "change");
    }); 
});