/*
    Created: 2025-02-27
    Author: Kārlis Grīnvalds
    Last edited: 2026-06-01
    Edited by: Kārlis Grīnvalds
*/

// All HTML files have this script attached which runs all the needed function for that page

// Executes and creates everything when the page loads in
$(document).ready(async function() {
    // CSRF BS T^T
    const csrfName = $("meta[name=\"csrf-name\"]").attr("content");
    let csrfHash = $("meta[name=\"csrf-token\"]").attr("content");
    $.ajaxPrefilter(function (options) {
        if (!options.type || !/^(POST|PUT|DELETE|PATCH)$/i.test(options.type)) {
            return;
        }
        if (options.data instanceof FormData) {
            options.data.append(csrfName, csrfHash);
            return;
        }
        if (typeof options.data === "string") {
            options.data = options.data ? options.data + "&" + csrfName + "=" + csrfHash : csrfName + "=" + csrfHash;
            return;
        }
        if (typeof options.data === "object" && options.data !== null) {
            options.data = $.extend({}, options.data);
            options.data[csrfName] = csrfHash;
            return;
        }
        options.data = {
            [csrfName]: csrfHash
        };
    });
    $(document).ajaxSuccess(function(event, xhr) {
        try {
            const res = JSON.parse(xhr.responseText);
            if (res.csrfHash) {
                csrfHash = res.csrfHash;
                $("meta[name=\"csrf-token\"]").attr("content", csrfHash);
            }
        }
        catch (e) {}
    });
    $("#UserActionBar").append("<a href=\"/\">Main</a><a href=\"/" + Topic() + "/Page:Main\">Topic</a>");
    $("#GoBackBar").append("<a href=\"/\">Main</a>");
    // Runs if user profile field exists
    if ($("#UserProfile").length > 0) {
        await $.ajax({
            url: "/user/session",
            method: "GET",
            success: async function(response) {
                // Checks user's session data
                if ("id" in response && "username" in response) {
                    // Is logged in
                    $("#UserProfile").append("Hello, <a href=\"/user\">" + response.username + "</a>! <a id=\"LogOutBtn\" href=\"#\">Log out</a>");
                    $("#LogOutBtn").on("click", async function() {
                        if (activeLock > 0) {
                            return;
                        }
                        LockUI();
                        await $.ajax({
                            url: "/user/logout",
                            method: "POST",
                            data: {},
                            success: function() {
                                activeLock++;
                                UnlockUI();
                                Link("/");
                            }
                        });
                    });
                }
                else {
                    // Is not logged in
                    $("#UserProfile").append("<a href=\"/create_account\">Create account</a> | <a href=\"/log_in\">Log in</a>");
                }
                let topicName = Topic();
                if (topicName.length > 0) {
                    await $.ajax({
                        url: "/user/permissions",
                        method: "GET",
                        data: {
                            topic: topicName,
                            select: ["create", "upload", "edit_entries", "edit_files", "delete_entries", "delete_files", "owner"]
                        },
                        success: function(permissions) {
                            if (Object.keys(permissions).length > 0) {
                                CreateDropDownMenu(permissions);
                                if (permissions.owner) {
                                    $("#DropDownMenu").append("<li><a href=\"/" + Topic() + "/Page:Admin\">Admin panel</a></li>");
                                }
                                else {
                                    if (permissions.create || permissions.edit_entries || permissions.delete_entries) {
                                        $("#DropDownMenu").append("<li><a href=\"/" + Topic() + "/Page:Entries\">Entries</a></li>");
                                    }
                                    if (permissions.upload || permissions.edit_files || permissions.delete_files) {
                                        $("#DropDownMenu").append("<li><a href=\"/" + Topic() + "/Page:Files\">Files</a></li>");
                                    }
                                }
                            }
                        }
                    });
                }
            }
        });
    }
    // Runs if search bar field exists
    if ($("#SearchBarDiv").length > 0) {
        // Executes function on button click
        $("#SearchBtn").on("click", async function() {
            if ($("#SearchField").val().length > 0) {
                Link("/" + Topic() + "/Page:Search?find=" + $("#SearchField").val());
            }
        });
        // Executes function on enter key press
        $("#SearchField").on("keypress", function(e) {
            if(e.which == 13){
                if ($("#SearchField").val().length > 0) {
                    Link("/" + Topic() + "/Page:Search?find=" + $("#SearchField").val());
                }
            }
        });
    }
    // Runs the page's function
    await Load();
    // Shows the page
    $("#Loader").fadeOut(300, function() {
        $("img.image-click").click(function(event) {
            $("#ViewImage").attr("src", event.target.src);
            let fileName = event.target.src.split("/load/")[1];
            $("#FileName").text(fileName);
            $("#FileName").attr("href", "/" + Topic() + "/File:" + fileName);
            $("body").css("overflow", "hidden");
            $("#ImageGallery").fadeIn(300);
        });
        $("#ImageGallery").click(function(event) {
            if (event.target.className.split("no-close").length != 2) {
                $("#ImageGallery").fadeOut(300);
                $("body").css("overflow", "");
            }
        });
    });
});

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

// Function that will redirect the user back to the previous page if there was
function RedirectBack(previous) {
    if (document.referrer.length > 0) {
        Link(document.referrer.split("?")[0]);
    }
    else {
        Link(previous);
    }
}

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

function CreateDropDownMenu(permissions) {
    if ($("#DropDownBtn").length <= 0) {
        let objs = Object.keys(permissions);
        for (let _ = 0; _ < objs.length; _++) {
            if (permissions[objs[_]] == true) {
                $("#UserActionBar").append("<a href=\"javascript:void(0);\" id=\"DropDownBtn\">...<div class=\"dropdown-menu\"><ul id=\"DropDownMenu\"></ul></div></a>");
                break;
            }
        }
    }
}


// for edit_page js
function DecodeHTMLSymbols(HTMLString) {
    const parser = new DOMParser();
    const doc = parser.parseFromString(HTMLString, "text/html");
    const textContent = doc.body.textContent || "";
    return textContent;
}

function AlertWindow(type, message, link, doPrevious) {
    $(".alert-icon").removeClass(type == "success" ? "error" : "success");
    $(".alert-icon").addClass(type == "error" ? "error" : "success");
    $("#AlertMessage").text(message);
    $("#AlertWindow").stop(true, true).fadeIn(200);
    let closed = false;
    function closeAlert() {
        if (closed) {
            return;
        }
        closed = true;
        $("#AlertWindow").fadeOut(200, function() {
            $(document).off("click.alertOutside");
            if (link && link.length > 0) {
                if (doPrevious) {
                    RedirectBack(link);
                } else {
                    Link(link);
                }
            }
        });
    }
    $("#AlertWindow").off("click").on("click", function(event) {
        event.stopPropagation();
        closeAlert();
    });
    $(document).off("click.alertOutside").on("click.alertOutside", function(event) {
        if (!$(event.target).closest("#AlertWindow").length) {
            closeAlert();
        }
    });
}

let activeLock = 0;

function LockUI() {
    if (activeLock > 0) {
        return;
    }
    activeLock++;
    $("#RequestWindow").fadeIn(200);
}

function UnlockUI() {
    if (activeLock <= 0) {
        return;
    }
    activeLock--;
    $("#RequestWindow").fadeOut(200);
}