/** @module others/rfcPreUploadUi */
import $ from "jquery";
import rmlOpts from "rmlopts";

import createFolderSelector from "../components/FolderSelector.js";
import store from "../store/index.js";
import hooks from "../util/hooks.js";

/**
 * Load data to a dropdown or show label that the folder is inherited from the AppTree.
 * This RFC is placed in the upload UI where you can select your files.
 *
 * @function preUploadUi
 * @listens module:util/hooks#wprfc/$function
 */
hooks.register("wprfc/preUploadUi", async function (data) {
    const compatView = !!$(this).parent(".rml-compat-preUploadUi").length;
    let attachmentsBrowser = $(this).parents(".attachments-browser");

    // Fallback to main media library page
    compatView && !attachmentsBrowser.length && (attachmentsBrowser = $(".attachments-browser"));

    if (attachmentsBrowser.length && !compatView) {
        $(this).parent().hide().prev().html(rmlOpts.others.lang.uploaderUsesLeftTree);
    } else {
        const span = $("<span/>")
            .addClass(compatView ? undefined : "attachments-filter-preUploadUi")
            .insertAfter($(this))
            .get(0);
        createFolderSelector(
            span,
            $(this).get(0),
            Object.assign(data, {
                style: {
                    maxWidth: 400,
                },
                // When in compat view raise the change event manually so it is saved
                onSelect:
                    compatView &&
                    function (node, input) {
                        attachmentsBrowser
                            .data("backboneView")
                            ?.controller.once("attachment:compat:ready", () => store.fetchCounts());
                        $(input).trigger("change");
                    },
            }),
        );
    }
});
