import Brick from "../core/brick.js";
import EdenModal from "../user-interface/common/eden-modal.js";
import { snackbar } from "../user-interface/common/eden-snackbar.js";
import { randomizeSvgSpriteCalls } from "../services/cleanup.js";
import t from "../i18n/index.js";
export default class Icon extends Brick {
    constructor({ block, element, parentBricks }) {
        super({ block, element, parentBricks });
        this.sprite = null;
        this.initElement = async () => {
            if (!this.spriteUrl) {
                return;
            }
            if (this.mode === "sprite") {
                await this.loadSpriteMode();
            }
            else {
                await this.loadIndexMode();
            }
        };
        this.updateIcon = (id) => {
            if (!id)
                return;
            const use = this.element.querySelector("use");
            if (!use)
                return;
            const attribute = use.hasAttribute("xlink:href") ? "xlink:href" : "href";
            const newHref = this.buildIconHref(id);
            use.setAttribute(attribute, newHref);
            randomizeSvgSpriteCalls();
        };
        const config = this.parseIconConfig();
        this.spriteUrl = config.spriteUrl;
        this.mode = config.mode;
        this.basePath = config.basePath;
        this.actions = [this.createEditAction()];
        this.initElement();
    }
    parseIconConfig() {
        const spriteUrl = window.EdenConfig.iconsSprite;
        if (!spriteUrl) {
            return { spriteUrl: "", mode: "sprite", basePath: "" };
        }
        const mode = spriteUrl.endsWith(".json") ? "index" : "sprite";
        const basePath = spriteUrl.split("/").slice(0, -1).join("/");
        return { spriteUrl, mode, basePath };
    }
    createEditAction() {
        return {
            tooltip: t("bricks.icon.edit-icon"),
            icon: "pen",
            action: async (e) => {
                const target = e.target;
                const button = target?.closest("button");
                if (!button)
                    return;
                const currentId = this.getCurrentIconId();
                if (!currentId) {
                    snackbar(t("snackbars.error"), "error");
                    return;
                }
                await this.openIconSelector(currentId);
            },
        };
    }
    getCurrentIconId() {
        const use = this.element.querySelector("use");
        if (!use)
            return null;
        const href = use.getAttribute("xlink:href") ?? use.getAttribute("href");
        if (!this.spriteUrl || !this.sprite || !href)
            return null;
        return this.mode === "index"
            ? (href.split("/").pop()?.split(".svg")[0] ?? null)
            : `#${href.split("#")[1] ?? ""}`;
    }
    async openIconSelector(currentId) {
        if (!this.sprite) {
            snackbar(t("snackbars.error"), "error");
            return;
        }
        const { default: EdenIconSelector } = await import("../user-interface/block/eden-icon-selector.js");
        const iconSelector = new EdenIconSelector(this.mode, this.sprite, currentId, this.basePath);
        const modal = new EdenModal({
            title: t("bricks.icon.select-icon"),
            icon: "icons",
            content: iconSelector,
            buttons: [
                {
                    cssClass: "cancel",
                    value: t("common.cancel"),
                },
                {
                    cssClass: "confirm",
                    value: t("common.confirm"),
                    onClick: () => this.updateIcon(iconSelector.currentId),
                },
            ],
        });
        document.body.appendChild(modal);
    }
    async loadSpriteMode() {
        const res = await fetch(this.spriteUrl);
        const html = await res.text();
        const parser = new DOMParser();
        const doc = parser.parseFromString(html, "text/html");
        const sprite = doc.querySelector("svg");
        if (sprite) {
            this.sprite = sprite;
        }
    }
    async loadIndexMode() {
        const res = await fetch(this.spriteUrl);
        const json = await res.json();
        this.sprite = json;
    }
    buildIconHref(id) {
        return this.mode === "sprite"
            ? `${this.spriteUrl}#${id}`
            : `${this.basePath}/${id}.svg#icon`;
    }
    activate() {
        this.element?.addEventListener("click", this.handleClick);
    }
    desactivate() {
        this.element?.removeEventListener("click", this.handleClick);
    }
}
