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

// Used for topic_form.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);
        CreateTopic();
    });
    // Input fields can run the same "on submit" function
    $("#TitleInputField").on("keypress", function(e) {
        // Checks, if the key press was enter
        if(e.which == 13 && !$("#EnterBtn").prop("disabled")){
            $("#EnterBtn").prop("disabled", true);
            CreateTopic();
        }
    });
}

// Checks the form and creates a new topic
async function CreateTopic() {
    $("#ErrorText").hide();
    $("#ErrorText").text("");
    let topicTitle = $("#TitleInputField").val().trim();
    // Check if all input fields are filled out
    if (topicTitle.length <= 0) {
        $("#ErrorText").text("Title input field must be filled!");
        $("#ErrorText").show();
        $("#EnterBtn").prop("disabled", false);
        return;
    }
    // Sends a POST request that will create a new topic
    if (activeLock > 0) {
        return;
    }
    LockUI();
    await $.ajax({
        url: "/topic",
        method: "POST",
        data: {title: topicTitle},
        success: function(response) {
            activeLock++;
            UnlockUI();
            AlertWindow("success", "Topic has been made!", "/" + response.name + "/Page:Main", true);
        },
        error: function(response) {
            UnlockUI();
            $("#ErrorText").text(response.responseJSON.messages.error);
            $("#ErrorText").show();
            $("#EnterBtn").prop("disabled", false);
        }
    });
}