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

// Used for file_upload.html

// :P
async function Load() {
    $("#UserActionBar").append("<a href=\"javascript:void(0);\" id=\"SaveChanges\">Save</a><a href=\"/" + Topic() + "/admin\">Cancel</a>");
    $("#UploadedFile").on("change", function() {
        $("#DisplayFile").empty();
        $("#FileUploadLabel").attr("value", 1);
        const uploadedFile = $("#UploadedFile")[0].files[0];
        $("#FileUploadLabel").text("File: " + uploadedFile.name);
        $("#FileDisplayName").val(uploadedFile.name);
        const reader = new FileReader();
        reader.onload = function (e) {
            if (uploadedFile.type.split("/")[0] == "image") {
                $("#DisplayFile").append("<img src=\"" + e.target.result + "\">");
            }
            else {
                $("#DisplayFile").append("<audio controls><source src=\"" + e.target.result + "\"></audio>");
            }
        };
        reader.readAsDataURL(uploadedFile);
    });
    $("#SaveChanges").on("click", async function() {
        // Checks if the fields have been filled
        if ($("#FileDisplayName").val().trim().length > 0 && $("#SaveChanges").attr("value") != "disabled" && $("#UploadedFile")[0].files.length == 1) {
            $("#SaveChanges").attr("value", "disabled");
            // Hides the error text
            $("#ErrorText").hide();
            $("#ErrorText").text("");
            // Gets the user who wants to make this entry
            let user_id = 0;
            await $.ajax({
                url: "/user/session",
                method: "PUT",
                success: function(response) {
                    if ("id" in response && "username" in response) {
                        // User was found
                        user_id = response.id;
                    }
                    else {
                        // If the user doesn't have an open session then user gets taken to error 404 page and the entry doesn't get created
                        Link("/error/404");
                    }
                }
            });
            const formData = new FormData();
            formData.append("user", user_id);
            formData.append("topic", Topic());
            formData.append("file", $("#UploadedFile")[0].files[0]);
            formData.append("name", $("#FileDisplayName").val());
            formData.append("description", $("#FileDescription").val());
            await $.ajax({
                url: "/file/upload",
                method: "POST",
                contentType: false,
                processData: false,
                data: formData,
                success: function() {
                    alert("File has been uploaded!");
                    Link("/" + Topic() + "/admin");
                },
                error: function(response) {
                    // 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 if ($("#UploadedFile")[0].files.length == 0) {
                $("#ErrorText").text("You must upload a file!");
            }
            else if ($("#FileDisplayName").val().trim().length == 0) {
                $("#ErrorText").text("File needs a display name!");
            }
            else {
                $("#ErrorText").text("Something has gone wrong!");
            }
        }
        $("#SaveChanges").attr("value", "");
    });
}