import wp from "wp";

import { SingleFile } from "../models/singleFile.js";
import { __ } from "../utils/i18n.js";

/**
 * Register a toolbar button: wp.media.view.RTGRegenerateButton
 */
function createToolbarButton() {
    const { Button } = wp.media.view;

    wp.media.view.RTGRegenerateButton = Button.extend({
        initialize(...args: any[]) {
            Button.prototype.initialize.apply(this, args);
            this.controller.on("selection:toggle", this.toggleDisabled, this);
        },

        toggleDisabled() {
            this.model.set("disabled", !this.controller.state().get("selection").length);
        },

        render(...args: any[]) {
            Button.prototype.render.apply(this, args);
            this.$el.addClass("rtg-regenerate-button");
            if (this.controller.isModeActive("select")) {
                this.$el.removeClass("hidden");
            } else {
                this.$el.addClass("hidden");
            }
            this.toggleDisabled();
            return this;
        },
    });
    return wp.media.view.RTGRegenerateButton;
}

/**
 * Add the toolbar button the the wp filter.
 */
function addToolbarButton() {
    if (!wp?.media?.view) {
        return;
    }

    const Button = createToolbarButton();
    const oldHandler = wp.media.view.AttachmentsBrowser.prototype.createToolbar;

    wp.media.view.AttachmentsBrowser.prototype.createToolbar = function (...args: any[]) {
        oldHandler.apply(this, args);
        this.toolbar.set(
            "rtgRegenerateButton",
            new Button({
                disabled: true,
                text: __("Regenerate"),
                controller: this.controller,
                priority: -60,
                async click() {
                    const selection = this.controller.state().get("selection");
                    if (selection.length) {
                        let id;
                        const ids = selection.map((o: any) => o.id);
                        this.controller.$el.fadeTo(200, 0.5);
                        while ((id = ids.pop())) {
                            await new SingleFile({
                                id,
                            }).regenerate(false, true);
                        }
                        this.controller.$el.fadeTo(200, 1);
                    }
                },
            }).render(),
        );
    };
}

export { addToolbarButton };
