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

// Used for user_settings.html

async function Load() {
    await $.ajax({
        url: "/topic/permissions",
        method: "GET",
        success: function(response) {
            if (response.length > 0) {
                for (let _ = 0; _ < response.length; _++) {
                    let html = "<td style=\"width: 20%\"><a href=\"/" + response[_].t_name + "/Page:Main\">" + response[_].t_title + "</a><br><span class=\"small\">" + response[_].t_name + "</span></td>";
                    html += "<td style=\"width: 10%\">" + ((response[_].t_public == 1) ? "public" : "private") + "</td>";
                    if (response[_].t_owner == true) {
                        html += "<td>Owner<br><span class=\"small\">Can do anything in the topic</span></td>";
                    }
                    else {
                        let previousLength_ = 0;
                        let text_ = "";
                        for (let value_ of Object.values(response[_].permissions)) {
                            text_ += value_;
                            if (previousLength_ < text_.length) {
                                text_ += ", ";
                                previousLength_ = text_.length;
                            }
                        }
                        html += "<td>" + text_.charAt(0).toUpperCase() + text_.slice(1, text_.length - 2) + "</td>";
                    }
                    html += "<td style=\"width: 10%\"><a href=\"/" + response[_].t_name + "/Page:Main\">Visit topic</a>" + ((response[_].t_owner == true) ? "<br><br><a href=\"/" + response[_].t_name + "/Page:Admin\">Admin panel</a>" : "") + "</td>";
                    $("#TopicList").append("<tr value=\"" + response[_].t_name + " " + response[_].t_title + "\">" + html + "</tr>");
                }
            }
            else {
                $("#TopicList").append("<tr><td class=\"no-topics\" colspan=\"4\">No topics are available</td></tr>");
            }
        }
    });
    $("#TopicSearchInput").on("input", function() {
        let tableRows = $("#TopicList tr:not(.yippee)");
        let search_ = $("#TopicSearchInput").val().toLowerCase();
        for (let _ = 0; _ < tableRows.length; _++) {
            let text_ = $(tableRows[_]).attr("value").toLowerCase();
            if (!text_.includes(search_)) {
                $(tableRows[_]).hide();
            }
            else {
                $(tableRows[_]).show();
            }
        }
    });
}