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

// Used for edit_topic.html

// Executes all the needed code
async function Load() {
    await $.ajax({
        url: "/topic/" + Topic(),
        method: "GET",
        success: function(response) {
            // Inserts all topic data in input fields
            $("#TopicTitle").val(DecodeHTMLSymbols(response[0].title));
            $("#TopicContent").val(DecodeHTMLSymbols(response[0].content));
            // Adds a function to save button
            $("#SaveChanges").on("click", async function() {
                // Checks, if the fields have been filled
                if ($("#TopicTitle").val().trim().length > 0 && $("#SaveChanges").attr("value") != "disabled") {
                    $("#SaveChanges").attr("value", "disabled");
                    // Hides the error text
                    $("#ErrorText").hide();
                    $("#ErrorText").text("");
                    // Prepares POST data
                    let data = {
                        title: $("#TopicTitle").val(),
                        content: $("#TopicContent").val()
                    };
                    // Updates the topic and returns the results
                    if (activeLock > 0) {
                        return;
                    }
                    LockUI();
                    await $.ajax({
                        url: "/topic/" + Topic(),
                        method: "POST",
                        data: data,
                        success: function() {
                            activeLock++;
                            UnlockUI();
                            AlertWindow("success", "Topic page has been updated!", "/" + Topic() + "/Page:Main", true);
                        },
                        error: function(response) {
                            UnlockUI();
                            // Outputs an error message
                            $("#ErrorText").show();
                            $("#ErrorText").text(response.responseJSON.messages.error);
                        }
                    });
                }
                else {
                    // Outputs an error message
                    $("#ErrorText").show();
                    $("#ErrorText").text("All input fields must be filled out!");
                }
            });
            $("#SaveChanges").attr("value", "");
            $("#CancelChanges").on("click", function() {
                RedirectBack("/" + Topic() + "/Page:Main");
            });
        },
        error: function(response) {
            Link("/error");
        }
    });
}