/*
    Created: 2026-04-13
    Author: Kārlis Grīnvalds
    Last edited: 2026-06-04
    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];
    // Prepares file edit page
    await $.ajax({
        url: "/file/" + fileName,
        method: "GET",
        success: async function(response) {
            $("#FileUploadLabel").text("File: " + fileName);
            ShowFile(fileName);
            $("#FileGivenName").val(DecodeHTMLSymbols(response[0].given));
            $("#FileDescription").val(DecodeHTMLSymbols(response[0].description));
            $("#SaveChanges").on("click", async function() {
                // Checks if the fields have been filled
                if ($("#SaveChanges").attr("value") != "disabled") {
                    $("#SaveChanges").attr("value", "disabled");
                    $("#ErrorText").hide();
                    $("#ErrorText").text("");
                    if (activeLock > 0) {
                        return;
                    }
                    LockUI();
                    await $.ajax({
                        url: "/file/" + response[0].id,
                        method: "POST",
                        data: {
                            topic: Topic(),
                            given: $("#FileGivenName").val(),
                            description: $("#FileDescription").val()
                        },
                        success: function() {
                            activeLock++;
                            UnlockUI();
                            AlertWindow("success", "File has been updated!", "/" + Topic() + "/File:" + fileName, true);
                        },
                        error: function(response) {
                            UnlockUI();
                            // Outputs the error message
                            $("#ErrorText").show();
                            $("#ErrorText").text(response.responseJSON.messages.error);
                            $("#SaveChanges").attr("value", "");
                        }
                    });
                }
                else {
                    // Outputs the error message
                    $("#ErrorText").show();
                    if ($("#SaveChanges").attr("value") == "disabled") {
                        $("#ErrorText").text("Loading!");
                    }
                    else {
                        $("#ErrorText").text("Something has gone wrong!");
                    }
                }
                $("#SaveChanges").attr("value", "");
            });
            $("#CancelChanges").on("click", function() {
                RedirectBack("/" + Topic() + "/File:" + fileName);
            });
            await $.ajax({
                url: "/user/permissions",
                method: "GET",
                data: {
                    topic: Topic(),
                    select: ["delete_files"]
                },
                success: function(permissions) {
                    if (Object.keys(permissions).length > 0) {
                        if (permissions.delete_files) {
                            $("div.form-btns").append("<button id=\"DeleteFile\">Delete</button>");
                            // Deletes the files and returns the results
                            $("#DeleteFile").on("click", async function() {
                                if ($("#SaveChanges").attr("value") != "disabled" && $("#Delete").attr("value") != "disabled") {
                                    $("#Delete").attr("value", "disabled");
                                    if (activeLock > 0) {
                                        return;
                                    }
                                    LockUI();
                                    await $.ajax({
                                        url: "/file/" + response[0].id,
                                        method: "DELETE",
                                        data: {
                                            topic: Topic()
                                        },
                                        success: function() {
                                            activeLock++;
                                            UnlockUI();
                                            AlertWindow("success", "File has been deleted!", "/" + Topic() + "/Page:Files", true);
                                        },
                                        error: function() {
                                            UnlockUI();
                                            // Something went wrong in the deletion
                                            $("#ErrorText").show();
                                            $("#ErrorText").text("Data is missing!");
                                        }
                                    });
                                }
                            });
                        }
                    }
                }
            });
        }
    });
}

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