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

// All HTML files have this script attached which runs all the need function for the page and other scripts

// When the page is done loading, runs all needed functions
$(document).ready(async function() {
    $("#UserActionBar").append("<a href=\"/" + Topic() + "/topic\">Main</a>");
    // Checks if the page has user profile field
    if ($("#UserProfile").length > 0) {
        await $.ajax({
            url: "/user/session",
            method: "PUT",
            success: function(response) {
                // Checks the session data to confirm the user is logged in
                if ("id" in response && "username" in response) {
                    // User is logged in
                    // Outputs a welcome message for the user and creates a log out button
                    $("#UserProfile").append("Hello, " + response.username + "! <a id=\"LogOutBtn\" href=\"#\">Log out</a>");
                    $("#LogOutBtn").on("click", async function() {
                        await $.ajax({
                            url: "/user/session",
                            method: "GET",
                            success: function(response) {
                                Link("/");
                            }
                        });
                    });
                }
                else {
                    // User is not logged in
                    // Creates sign up and log in buttons with functions
                    $("#UserProfile").append("<a href=\"/create_account\">Create account</a> | <a href=\"/log_in\">Log in</a>");
                }
            }
        });
    }
    // Checks if the page has a search bar field
    if ($("#SearchBarDiv").length > 0) {
        // Gives functions to the button and input field that will run the same function on click or enter
        $("#SearchBtn").on("click", async function() {
            if ($("#SearchField").val().length > 0) {
                Link("/" + Topic() + "/search?find=" + $("#SearchField").val());
            }
        });
        $("#SearchField").on("keypress", function(e) {
            // Checks if the key press was enter
            if(e.which == 13){
                if ($("#SearchField").val().length > 0) {
                    Link("/" + Topic() + "/search?find=" + $("#SearchField").val());
                }
            }
        });
    }
    // Default function for all JavaScript files gets ran
    Load();
});

// Function that will send the user to the given url
function Link(address) {
	document.location.href = address;
}

// Gets the topic name from url
function Topic() {
    const topicName = window.location.href.split(":8080/")[1].split("/")[0];
    return decodeURI(topicName);
}