/*
    Created: 2025-02-27
    Author: Kārlis Grīnvalds
    Last edited: 2026-06-04
    Edited by: Kārlis Grīnvalds
*/

// Used for create_account.html

// Adds functions to a button and input fields
async function Load() {
    // The enter button gets an "on submit" function
    $("#EnterBtn").on("click", function() {
        $("#EnterBtn").prop("disabled", true);
        SignUp();
    });
    // Input fields can run the same "on submit" function
    $("#UserNameInputField, #EmailInputField, #PasswordInputField, #VerifyPasswordInputField").on("keypress", function(e) {
        // Checks, if the key press was enter
        if(e.which == 13 && !$("#EnterBtn").prop("disabled")){
            $("#EnterBtn").prop("disabled", true);
            SignUp();
        }
    });
    // Adds function to a checkbox to show the inputted password
    $("#ShowPasswordBtn").on("change", function() {
        if ($("#ShowPasswordBtn:checked").val() === undefined) {
            $("#PasswordInputField").attr("type", "password");
            $("#VerifyPasswordInputField").attr("type", "password");
        }
        else {
            $("#PasswordInputField").attr("type", "text");
            $("#VerifyPasswordInputField").attr("type", "text");
        }
    });
}

// Does the sign up process
async function SignUp() {
    $("#ErrorText").hide();
    $("#ErrorText").text("");
    let data = {
        username: $("#UserNameInputField").val().trim(),
        email: $("#EmailInputField").val().trim(),
        password: $("#PasswordInputField").val().trim(),
    };
    // Check if all input fields are filled out
    if (data.username.length <= 0 || data.email.length <= 0 || data.password.length <= 0 || $("#VerifyPasswordInputField").val().trim().length <= 0) {
        ReturnError("All input fields need to be filled!");
        return;
    }
    // Check for length
    if (data.username.length < 4) {
        ReturnError("Username too short!");
        return;
    }
    if (data.username.length > 20) {
        ReturnError("Username too long!");
        return;
    }
    if (data.email.length < 5 || data.email.length >= 50) {
        ReturnError("Email invalid!");
        return;
    }
    if (data.password.length < 8) {
        ReturnError("Password too short!");
        return;
    }
    // Check if both passwords are equal
    if ($("#VerifyPasswordInputField").val().trim() != data.password) {
        ReturnError("Passwords don't match!");
        return;
    }
    // Check for valid characters
    let characterCheck = "";
    for (let _ = 0; _ < Object.keys(data).length; _++) {
        characterCheck = CheckCharacters(data[Object.keys(data)[_]], Object.keys(data)[_]);
        if (characterCheck.length > 0) {
            ReturnError(characterCheck);
            return;
        }
    }
    if (activeLock > 0) {
        return;
    }
    LockUI();
    // Everything passed and met requirements - it can be sent
    await $.ajax({
        url: "/user",
        method: "POST",
        data: data,
        success: function() {
            activeLock++;
            UnlockUI();
            AlertWindow("success", "Account has been created! Please log in!", "/log_in", false);
        },
        error: function(response) {
            UnlockUI();
            ReturnError(response.responseJSON.messages.error);
        }
    });
}

// Returns error message
function ReturnError(message) {
    $("#ErrorText").text(message);
    $("#ErrorText").show();
    $("#EnterBtn").prop("disabled", false);
}

// Checks for valid characters
function CheckCharacters(string, type) {
    if (string.split(" ").length != 1) {
        return "Remove spaces from " + type + " input field!";
    }
    let msg = "";
    switch (type) {
        case "username":
            // Checks if the given username has any illegal characters
            if (string.match("^[a-zA-Z0-9]*$") == null) {
                msg = "Username contains illegal characters!";
            }
            break;
        case "email":
            // Checks if the given email has @ and .
            let emailComponents = string.split("@");
            if (emailComponents.length == 2 && emailComponents[0].length > 0 && emailComponents[1].length > 0) {
                let domainName = emailComponents[1].split(".");
                if (domainName.length == 2 && domainName[0].length > 0 && domainName[1].length > 0) {
                    break;
                }
                else {
                    msg = "Invalid email!";
                }
            }
            else {
                msg = "Invalid email!";
            }
            break;
        case "password":
            // Checks if the password has met the requirements
            if (string.match("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[!@#$%^&*()_=]).{8,}$") == null) {
                msg = "Password character requirements haven't been met!";
            }
            break;
        default:
            // Some mystical bullshit has happened
            msg = "System had an oopsie, please, report this!";
            break;
    }
    return msg;
}