import $ from "jquery";
import { store as rmlStore } from "rml";

import { Hooks } from "../utils/hooks.js";

import type { ActionPhysicalUpdatedParams } from "../utils/hooks.js";

function applyUrlReplace() {
    Hooks.handler.addAction(
        Hooks.ACTION_PHYSICAL_UPDATED,
        "internal/urlReplace",
        ({ done: { attachment, currentFolderId }, newSizes }: ActionPhysicalUpdatedParams) => {
            // Update backbone models
            $(".attachments-browser").each(function () {
                const backboneView = $(this).data("backboneView");
                if (backboneView) {
                    const { controller } = backboneView;
                    const model = controller.browserView.attachments.collection.get(attachment);
                    if (model) {
                        const sizes = $.extend(true, {}, model.get("sizes"));
                        $.each(newSizes, (k, v) => {
                            sizes[k] && (sizes[k].url = v);
                        });
                        model.set("sizes", sizes);
                        model.set("url", newSizes.full);
                    } else {
                        // The model does not exist, so make the folder to refresh
                        rmlStore.addFoldersNeedsRefresh("all");
                        rmlStore.addFoldersNeedsRefresh(currentFolderId);
                    }
                }
            });

            // Update attachment modal URL input
            $(`.attachment-details[data-id=${attachment}] [data-setting="url"] input`).val(newSizes.full);
        },
    );
}

export { applyUrlReplace };
