/*
    Created: 2025-02-27
    Author: Kārlis Grīnvalds
    Last edited: 2025-12-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();
        }
    });
}

// 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.username.length <= 0 && data.username.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) {
        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;
        }
    }
    // Everything passed and met requirements - it can be sent
    await $.ajax({
        url: "/user",
        method: "POST",
        data: data,
        success: function() {
            alert("Account created! Please, log in!");
            Link("/log_in");
        },
        error: function(response) {
            ReturnError(response.responseJSON.messages.error);
            return;
        }
    });
}

// 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":
            if (string.match("^[a-zA-Z0-9]*$") == null) {
                msg = "Username contains illegal characters!";
            }
            break;
        case "email":
            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":
            if (string.match("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[!@#$%^&*()_=]).{8,}$") == null) {
                msg = "Password character requirements having been met!";
            }
            break;
        default:
            msg = "System had an oopsie, please, report this!";
            break;
    }
    return msg;
}