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

// Used for entries.html

// Executes all the needed code
async function Load() {
    // Gets all entries
    await $.ajax({
        url: "/entries/" + Topic(),
        method: "GET",
        success: async function(response) {
            await $.ajax({
                url: "/user/permissions",
                method: "GET",
                data: {
                    topic: Topic(),
                    select: ["create", "edit_entries"]
                },
                success: function(permissions) {
                    for (let _ = 0; _ < response.length; _++) {
                        let appendString = "<td>" + response[_].title + "</td><td>" + response[_].created_at + "</td>";
                        if (response[_].edited_at != null) {
                            appendString += "<td>" + response[_].edited_at + "</td>";
                        }
                        else {
                            appendString += "<td> - </td>";
                        }
                        appendString += "<td><a href=\"/" + Topic() + "/" + response[_].name + "\">View</a>";
                        if (permissions.edit_entries) {
                            appendString += " <a href=\"/" + Topic() + "/" + response[_].name + "?a=edit\">Edit</a>";
                        }
                        $("#TableOfEntries").append("<tr>" + appendString + "</td></tr>");
                    }
                    if (response.length <= 0) {
                        $("#TableOfEntries").append("<tr><td class=\"no-entries\" colspan=\"4\">No entries are available</td></tr>");
                    }
                    if (Object.keys(permissions).length > 0) {
                        if (permissions.create) {
                            CreateDropDownMenu(permissions);
                            $("#DropDownMenu").append("<li><a href=\"/" + Topic() + "/Page:Create\">Create entry</a></li>");
                        }
                    }
                }
            });
        }
    });
    $("#EntrySearchInput").on("input", function() {
        let tableRows = $("#TableOfEntries tr:not(.yippee)");
        let search_ = $("#EntrySearchInput").val().toLowerCase();
        for (let _ = 0; _ < tableRows.length; _++) {
            let text_ = tableRows[_].innerHTML.split("</td>")[0].substring(4).toLowerCase();
            if (!text_.includes(search_)) {
                $(tableRows[_]).hide();
            }
            else {
                $(tableRows[_]).show();
            }
        }
    });
}