/*
    Created: 2025-12-04
    Author: Kārlis Grīnvalds
    Last edited: 2025-12-04
    Edited by: Kārlis Grīnvalds
*/

// Used for entry.html

// Runs all the needed functions for the current page
async function Load() {
    // Gets the url parameter
    const url = window.location.href.split("?a=")[1].split("&i=");
    const entryAction = url[0];
    const entryId = url[1];
    switch (entryAction) {
        case "view":
            $("#MainContainer").html('<h1 id="EntryTitle" class="title-text"></h1><hr><div id="EntryContent" class="entry-content"></div>');
            await $.ajax({
                url: "/entry/" + entryId,
                method: "GET",
                success: async function(response) {
                    $("#EntryTitle").text(response[0].title);
                    $("footer").append("Created at: " + response[0].created_at);
                    if (response[0].edited_at != null) {
                        // If the entry has been edited then this will also get displayed
                        $("footer").append("<br>Last edited: " + response[0].edited_at);
                    }
                    let pageContent = LoadContent(response[0].content);
                    $("#EntryContent").append(FormatText(pageContent));
                    CreateContentList(pageContent);
                }
            });
            break;
        case "create":
            $("#MainContainer").html('<div class="form"><h1>Entry data</h1><input id="EntryTitle" placeholder="Title"><br><textarea id="EntryContent" placeholder="Content"></textarea></div><p id="ErrorText" class="error-text"></p>');
            $("#UserActionBar").append("<a href=\"javascript:void(0);\" id=\"SaveChanges\">Save</a><a href=\"/" + Topic() + "/admin\">Cancel</a>");
            $("#SaveChanges").on("click", async function() {
                // Checks if the fields have been filled
                if ($("#EntryTitle").val().trim().length > 0 && $("#SaveChanges").attr("value") != "disabled") {
                    $("#SaveChanges").attr("value", "disabled");
                    // Hides the error text
                    $("#ErrorText").hide();
                    $("#ErrorText").text("");
                    // Gets the user who wants to make this entry
                    let user_id = 0;
                    await $.ajax({
                        url: "/user/session",
                        method: "PUT",
                        success: function(response) {
                            if ("id" in response && "username" in response) {
                                // User was found
                                user_id = response.id;
                            }
                            else {
                                // If the user doesn't have an open session then user gets taken to error 404 page and the entry doesn't get created
                                Link("/error/404");
                            }
                        }
                    });
                    // Prepares POST data
                    let data = {
                        user: user_id,
                        topic: Topic(),
                        title: $("#EntryTitle").val(),
                        content: $("#EntryContent").val(),
                    };
                    // Creates the entry and returns the results
                    await $.ajax({
                        url: "/entry/0",
                        method: "POST",
                        data: data,
                        success: function() {
                            // Entry has been created!
                            alert("Entry has been created!");
                            // Returns user to main page
                            Link("/" + Topic() + "/admin");
                        },
                        error: function(response) {
                            // Outputs the error message
                            $("#ErrorText").show();
                            $("#ErrorText").text(response.responseJSON.messages.error);
                        }
                    }); 
                }
                else {
                    // Outputs the error message
                    $("#ErrorText").show();
                    if ($("#SaveChanges").attr("value") == "disabled") {
                        $("#ErrorText").text("Loading!");
                    }
                    else {
                        $("#ErrorText").text("Entry needs a title!");
                    }
                }
                $("#SaveChanges").attr("value", "");
            });
            break;
        case "edit":
            $("#MainContainer").html('<div class="form"><h1>Entry data</h1><input id="EntryTitle" placeholder="Title"><br><textarea id="EntryContent" placeholder="Content"></textarea></div><p id="ErrorText" class="error-text"></p>');
            await $.ajax({
                url: "/entry/" + entryId,
                method: "GET",
                success: async function(response) {
                    // Checks if the user can edit the entry
                    await $.ajax({
                        url: "/entry/permission/" + response[0].id,
                        method: "GET",
                        success: function(answer) {
                            if (!answer) {
                                // User wasn't allowed to edit the entry
                                Link("/error/403");
                            }
                        }
                    });
                    // Creates all the actions that the user can do - save or delete the entry, or don't save any changes
                    $("#UserActionBar").append("<a href=\"javascript:void(0);\" id=\"SaveChanges\">Save</a><a href=\"/" + Topic() + "/entry?a=view&i=" + entryId + "\">Cancel</a><a href=\"javascript:void(0);\" id=\"Delete\">Delete</a>");
                    // Deletes the entry and returns the results
                    $("#Delete").on("click", async function() {
                        if ($("#SaveChanges").attr("value") != "disabled" && $("#Delete").attr("value") != "disabled") {
                            $("#Delete").attr("value", "disabled");
                            await $.ajax({
                                url: "/entry/" + entryId,
                                method: "DELETE",
                                success: function() {
                                    // Entry has been deleted succesfully!
                                    alert("Entry has been deleted!");
                                    Link("/" + Topic() + "/main");
                                },
                                error: function() {
                                    // Something went wrong in the deletion
                                    $("#ErrorText").show();
                                    $("#ErrorText").text("Data is missing!");
                                }
                            });
                        }
                    });
                    // Inserts all entry data in input fields
                    $("#EntryTitle").val(response[0].title);
                    $("#EntryContent").val(response[0].content);
                    // Adds a function to save button
                    $("#SaveChanges").on("click", async function() {
                        // Checks, if the fields have been filled
                        if ($("#EntryTitle").val().trim().length > 0 && $("#SaveChanges").attr("value") != "disabled" && $("#Delete").attr("value") != "disabled") {
                            $("#SaveChanges").attr("value", "disabled");
                            // Hides the error text
                            $("#ErrorText").hide();
                            $("#ErrorText").text("");
                            // Prepares POST data
                            let data = {
                                title: $("#EntryTitle").val(),
                                content: $("#EntryContent").val()
                            };
                            // Updates the entry and returns the results
                            await $.ajax({
                                url: "/entry/" + entryId,
                                method: "POST",
                                data: data,
                                success: function() {
                                    // Entry has been updated!
                                    alert("Entry has been updated!");
                                    // Returns user to the entry
                                    Link("/" + Topic() + "/entry?a=view&i=" + entryId);
                                },
                                error: function(response) {
                                    // 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", "");
                }
            });
            break;
        default:
            Link("/error/404");
            break;
    }
}