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

// Used for file.html

// Executes all the needed code
async function Load() {
    // Gets the url parameter
    const url = window.location.href.split("/File:")[1].split("?a=");
    const fileName = url[0];
    // Loads file information
    $("#FileDisplayName").html(fileName);
    await $.ajax({
        url: "/file/" + fileName,
        method: "GET",
        success: async function(response) {
            ShowFile(fileName);
            if (response[0].given != null) {
                if (response[0].given.length > 0) {
                    $("#FileDescription").before("<h4>Given name: " + response[0].given + "</h4>");
                }
                else {
                    $("#FileDescription").before("<p style=\"color: rgb(100, 100, 100); font-size: 80%;\">No user given name..</p>");
                }
            }
            else {
                $("#FileDescription").before("<p style=\"color: rgb(100, 100, 100); font-size: 80%;\">No user given name..</p>");
            }
            if (response[0].description.trim().length <= 0) {
                $("#FileDescription").append("<br><p style=\"color: rgb(100, 100, 100); font-size: 80%;\">No description added..</p>");
            }
            else {
                $("#FileDescription").append("<br>" + LoadContent(response[0].description));
            }
            $("#FileDescription").append("<hr><p>For use case:</p><pre>[[file=\"" + fileName + "\"]]</pre>");
            $("footer").append("Uploaded: " + response[0].created_at);
            if (response[0].edited_at != null) {
                $("footer").append("<br>Last edited: " + response[0].edited_at);
            }
        }
    });
    await $.ajax({
        url: "/user/permissions",
        method: "GET",
        data: {
            topic: Topic(),
            select: ["edit_files"]
        },
        success: function(permissions) {
            if (Object.keys(permissions).length > 0) {
                if (permissions.edit_files) {
                    CreateDropDownMenu(permissions);
                    $("#DropDownMenu").append("<li><a href=\"?a=edit\">Edit file</a></li>");
                }
            }
        }
    });
}

// Displays file
function ShowFile(fileName) {
    switch (fileName.split(".")[1]) {
        case "gif":
        case "jpeg":
        case "jpg":
        case "png":
        case "webp":
            $("#DisplayFile").append("<a href=\"load/" + fileName + "\"><img src=\"load/" + fileName + "\"></a>");
            break;
        case "mp3":
        case "wav":
            $("#DisplayFile").append("<audio controls><source src=\"load/" + fileName + "\"></audio>");
            break;
        default:
            $("#DisplayFile").append("Not supported");
            break;
    }
}