import $ from "jquery";

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

function addTableBulkAction() {
    const OPTION_NAME = "rtg_regenerate";
    const $table = $(".wp-list-table.media");
    const $select = $(".bulkactions > #bulk-action-selector-top, .bulkactions > #bulk-action-selector-bottom");

    // Add dropdown item and listen to the button
    $select.length &&
        $table.length &&
        $select
            .append(`<option value="${OPTION_NAME}">${__("Regenerate")}</option>`)
            .next(".button")
            .click(function (e) {
                if ($(this).prev("select").val() === OPTION_NAME) {
                    // Collect selected ids
                    const ids = $table
                        .find('[name="media[]"]:checked')
                        .map(function () {
                            return +$(this).val();
                        })
                        .toArray();
                    if (ids.length) {
                        // Regenerate in async method
                        $table.stop().fadeTo(200, 0.5);
                        (async () => {
                            let id;
                            while ((id = ids.pop())) {
                                await new SingleFile({
                                    id,
                                }).regenerate(false, true);
                            }
                            $table.stop().fadeTo(200, 1);
                        })();
                    }
                    return e.preventDefault();
                }
            });
}

export { addTableBulkAction };
