import Brick from "../core/brick.js";
import EdenModal from "../user-interface/common/eden-modal.js";
import t from "../i18n/index.js";
export default class Picture extends Brick {
    constructor({ block, element, parentBricks, options, markup, }) {
        super({ block, element, parentBricks });
        this.buildActions = () => {
            const baseActions = [this.createReplaceImageAction()];
            const cropActions = this.shouldShowCropAction()
                ? [this.createCropAction()]
                : [];
            const otherActions = [
                this.createImageSettingsAction(),
                this.createRemoveImageAction(),
            ];
            this.actions = [...baseActions, ...cropActions, ...otherActions];
        };
        this.refresh = async () => {
            if (!this.block)
                return;
            this.block.hideUi();
            this.block.actionsGroups = [];
            this.buildActions();
            await this.block.showUi();
        };
        this.openFilePicker = async (withMetadata) => {
            if (!this.image)
                return;
            const dimensions = this.getImageDimensions();
            const metadata = withMetadata
                ? this.image.getAttribute("data-metadata") ?? undefined
                : undefined;
            const { default: FileManagerModal } = await import("../user-interface/plugin/file-manager-modal.js");
            new FileManagerModal({
                callback: this.createSimpleImageCallback(),
                width: dimensions.width,
                height: dimensions.height,
                metadata,
            });
        };
        this.openMutlipleSizedImageModal = async () => {
            if (!this.image || !this.sizes)
                return;
            const { default: MultipleSizedImagesModal } = await import("../user-interface/plugin/multiple-sized-images-modal.js");
            new MultipleSizedImagesModal(this.element, this.createMultipleSizedImageCallback(), this.sizes, this.markup).init();
        };
        this.preSave = () => {
            if (!this.image)
                return;
            const hasExplicitDimensions = this.image.hasAttribute("width") && this.image.hasAttribute("height");
            if (hasExplicitDimensions) {
                if (this.image.getAttribute("loading") !== "eager") {
                    const { top, left } = this.image.getBoundingClientRect();
                    const isInViewport = top < 600 && left < 1000;
                    this.image.setAttribute("loading", isInViewport ? "eager" : "lazy");
                }
            }
            else {
                if (this.image.getAttribute("loading") !== "eager") {
                    this.image.removeAttribute("loading");
                }
            }
        };
        this.updateAttributes = (description, credits, loading) => {
            this.updateAlt(description);
            this.updateCredits(credits);
            this.updateLoading(loading);
        };
        this.updateAlt = (text) => {
            const image = this.element?.querySelector("img");
            if (!image)
                return;
            if (text) {
                image.setAttribute("alt", text);
            }
            else {
                image.removeAttribute("alt");
            }
        };
        this.updateCredits = (text) => {
            if (text) {
                this.element?.setAttribute("data-credits", text);
            }
            else {
                this.element?.removeAttribute("data-credits");
            }
        };
        this.updateLoading = (loading) => {
            if (!this.image)
                return;
            this.image.setAttribute("loading", loading);
        };
        this.activate = () => {
            if (!this.element)
                return;
            this.element.addEventListener("click", this.handleClick);
        };
        this.desactivate = () => {
            if (!this.element)
                return;
            this.element.removeEventListener("click", this.handleClick);
        };
        this.image = this.element?.querySelector("img") ?? null;
        this.sizes = options?.sizes;
        this.markup = markup;
        this.buildActions();
    }
    shouldShowCropAction() {
        const hasSizes = Boolean(this.sizes);
        const hasMetadata = this.image?.hasAttribute("data-metadata");
        return !hasSizes && Boolean(hasMetadata);
    }
    createReplaceImageAction() {
        return {
            tooltip: t("bricks.picture.replace-image"),
            icon: "image",
            action: async () => {
                if (!this.sizes) {
                    this.openFilePicker();
                }
                else {
                    this.openMutlipleSizedImageModal();
                }
            },
        };
    }
    createCropAction() {
        return {
            tooltip: t("bricks.picture.crop-image"),
            icon: "crop",
            action: async () => {
                this.openFilePicker(true);
            },
        };
    }
    createImageSettingsAction() {
        return {
            tooltip: t("bricks.picture.image-settings"),
            icon: "tune",
            action: async () => {
                if (!this.image)
                    return;
                const attributes = this.getImageAttributes();
                const { default: ImageSettingsModal } = await import("../user-interface/plugin/image-settings-modal.js");
                new ImageSettingsModal(this.updateAttributes, attributes.description, attributes.credits, attributes.lazyLoading).init();
            },
        };
    }
    createRemoveImageAction() {
        return {
            tooltip: t("bricks.picture.remove-image"),
            icon: "close",
            action: async () => {
                const modal = new EdenModal({
                    icon: "image",
                    title: t("bricks.picture.remove-image"),
                    content: t("bricks.picture.remove-image-confirm"),
                    buttons: [
                        {
                            value: t("common.cancel"),
                            cssClass: "cancel",
                        },
                        {
                            value: t("common.remove"),
                            onClick: () => {
                                if (!this.markup)
                                    return;
                                this.element.innerHTML = this.markup;
                                this.image?.removeAttribute("data-metadata");
                                this.image = this.element?.querySelector("img") ?? null;
                            },
                            cssClass: "confirm",
                            autofocus: true,
                        },
                    ],
                    closeButton: false,
                });
                document.body.appendChild(modal);
            },
        };
    }
    getImageAttributes() {
        return {
            description: this.image?.getAttribute("alt") ?? "",
            credits: this.element?.getAttribute("data-credits") ?? "",
            lazyLoading: this.image?.getAttribute("loading") === "lazy",
        };
    }
    getImageDimensions() {
        if (!this.image) {
            return {};
        }
        return {
            width: this.image.hasAttribute("width")
                ? parseInt(this.image.getAttribute("width") ?? "0", 10) || undefined
                : undefined,
            height: this.image.hasAttribute("height")
                ? parseInt(this.image.getAttribute("height") ?? "0", 10) || undefined
                : undefined,
        };
    }
    createSimpleImageCallback() {
        return (url, metadata) => {
            if (!url || !this.image)
                return;
            this.image.src = url;
            this.image.setAttribute("data-metadata", metadata);
            this.element.innerHTML = "";
            this.element.appendChild(this.image);
            this.refresh();
        };
    }
    createMultipleSizedImageCallback() {
        return (results) => {
            if (!this.sizes || !this.image)
                return;
            results.forEach(({ key, src, metadata }) => {
                if (key === "default") {
                    this.createSimpleImageCallback()(src, metadata);
                    return;
                }
                if (!src)
                    return;
                const isNotDefaultSrc = this.sizes[key].src !== src;
                if (isNotDefaultSrc) {
                    const source = document.createElement("source");
                    source.srcset = src;
                    source.media = `(${key})`;
                    source.setAttribute("data-metadata", metadata);
                    this.element.prepend(source);
                }
            });
            this.refresh();
        };
    }
}
