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

// Used for admin_panel.html

// Load admin panel
async function Load() {
    $("#UserActionBar").append("<a href=\"/" + Topic() + "/entry?a=create\">Create entry</a><a href=\"/" + Topic() + "/upload\">Upload file</a>");
    $("#TopicLink").attr("href", "/" + Topic() + "/topic?a=edit");
    await $.ajax({
        url: "/entries/" + Topic(),
        method: "GET",
        success: function(response) {
            for (let _ = 0; _ < response.length; _++) {
                let appendString = "<tr><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() + "/entry?a=view&i=" + response[_].id + "\">View</a> <a href=\"/" + Topic() + "/entry/entry?a=edit&i=" + response[_].id + "\">Edit</a></td></tr>";
                $("#TableOfEntries").append(appendString);
            }
        }
    });
    await $.ajax({
        url: "/" + Topic() + "/files",
        method: "GET",
        success: async function(response) {
            for (let _ = 0; _ < response.length; _++) {
                let appendString = "<tr><td id=\"file" + response[_].id + "\"></td><td>" + response[_].name + "</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() + "/file?file=" + response[_].file + "\">View</a> <a href=\"/" + Topic() + "/file/edit?file=" + response[_].file + "\">Edit</a></td></tr>";
                $("#TableOfFiles").append(appendString);
                switch (response[_].file.split(".")[1]) {
                    case "gif":
                    case "jpeg":
                    case "jpg":
                    case "png":
                    case "webp":
                        $("#file" + response[_].id).append("<img src=\"/" + Topic() + "/load/" + response[_].file + "\">");
                        break;
                    case "mp3":
                    case "wav":
                        $("#file" + response[_].id).append("<audio controls><source src=\"/" + Topic() + "/load/" + response[_].file + "\"></audio>");
                        break;
                    default:
                        $("#file" + response[_].id).append("Not supported");
                        break;
                }
            }
        }
    });
}