import Brick, { setEditable, unsetEditable } from "../core/brick.js";
import { htmlStringToElement } from "../services/html.js";
import { snackbar } from "../user-interface/common/eden-snackbar.js";
import EdenModal from "../user-interface/common/eden-modal.js";
import t from "../i18n/index.js";
export default class Table extends Brick {
    constructor({ block, element, parentBricks, rows }) {
        super({ block, element, parentBricks });
        this.tools = "";
        this.rows = rows;
        if (!rows) {
            throw new Error("No row specified");
        }
        this.actions = this.createActions();
    }
    createActions() {
        return [
            this.createAddRowAction(),
            this.createDuplicateAction(),
            this.createMoveUpAction(),
            this.createMoveDownAction(),
            this.createRemoveAction(),
        ];
    }
    createAddRowAction() {
        return {
            icon: "plus",
            tooltip: t("bricks.table.add-row"),
            action: this.rows.map((row, index) => ({
                name: row.name,
                action: () => this.addRow(row.markup, index),
            })),
        };
    }
    addRow(markup, index) {
        const newLine = htmlStringToElement(markup);
        if (!newLine)
            return;
        newLine.dataset.rowformat = String(index);
        const tr = this.selectedLine();
        if (tr) {
            tr.insertAdjacentElement("afterend", newLine);
        }
        else {
            this.element.insertAdjacentElement("beforeend", newLine);
        }
        setEditable(Array.from(newLine.querySelectorAll("td:not(.link), th:not(.link)")));
        const firstChild = newLine.querySelector(":first-child");
        firstChild?.focus();
    }
    createDuplicateAction() {
        return {
            tooltip: t("common.duplicate"),
            icon: "duplicate",
            action: () => this.applyOnLine((tr) => {
                tr.insertAdjacentElement("afterend", tr.cloneNode(true));
            }),
        };
    }
    createMoveUpAction() {
        return {
            tooltip: t("bricks.table.move-up"),
            icon: "chevron_up",
            action: () => this.applyOnLine((tr) => {
                const sibling = tr.previousSibling;
                sibling?.insertAdjacentElement("beforebegin", tr);
            }),
        };
    }
    createMoveDownAction() {
        return {
            tooltip: t("bricks.table.move-down"),
            icon: "chevron_down",
            action: () => this.applyOnLine((tr) => {
                const sibling = tr.nextSibling;
                sibling?.insertAdjacentElement("afterend", tr);
            }),
        };
    }
    createRemoveAction() {
        return {
            tooltip: t("common.remove"),
            icon: "delete",
            action: () => this.handleRemoveRow(),
        };
    }
    handleRemoveRow() {
        const rowCount = this.element.querySelectorAll("tr").length;
        if (rowCount <= 1) {
            snackbar(t("snackbars.cannot-delete-last-row"), "warning");
            return;
        }
        const modal = new EdenModal({
            icon: "delete",
            title: t("bricks.table.remove-row"),
            content: t("bricks.table.remove-row-confirm"),
            buttons: [
                {
                    value: t("common.cancel"),
                    cssClass: "cancel",
                },
                {
                    value: t("common.remove"),
                    onClick: () => this.applyOnLine((tr) => tr.remove()),
                    cssClass: "confirm",
                    autofocus: true,
                },
            ],
            closeButton: false,
        });
        document.body.appendChild(modal);
    }
    selectedLine() {
        try {
            const container = document.getSelection()?.getRangeAt(0)
                .startContainer;
            return container ? this.hasParents(container, "tr") ?? null : null;
        }
        catch {
            return null;
        }
    }
    applyOnLine(fn) {
        const tr = this.selectedLine();
        if (!tr) {
            snackbar(t("snackbars.select-line"), "warning");
            return;
        }
        fn(tr);
        const firstChild = tr.querySelector(":first-child");
        firstChild?.focus();
    }
    activate() {
        if (!this.element)
            return;
        this.element.addEventListener("click", this.handleClick);
        setEditable(Array.from(this.element.querySelectorAll("td:not(.link), th:not(.link)")));
    }
    desactivate() {
        if (!this.element)
            return;
        this.element.removeEventListener("click", this.handleClick);
        unsetEditable(Array.from(this.element.querySelectorAll("td:not(.link), th:not(.link)")));
    }
}
