import t from "../../i18n/index.js";
import { EdenEvents, fireEvent } from "../../services/event.js";
import { isLocalhost, smoothScrollTo } from "../../services/util.js";
import buildUuid from "../../services/uuid.js";
import EdenModal from "../../user-interface/common/eden-modal.js";
import { snackbar } from "../../user-interface/common/eden-snackbar.js";
export async function copyElement(block, elementType, cutMode) {
    block.editor?.desactivate();
    const copy = (elementType === "editor" && block.editor
        ? block.editor.element.cloneNode(true)
        : block.element.cloneNode(true));
    if (cutMode) {
        await block.remove();
    }
    block.editor?.activate();
    await navigator.clipboard.writeText(`fromEden:${elementType === "editor" ? copy.innerHTML : copy.outerHTML}`);
}
export function createManualCopyAction(block, elementType, cutMode) {
    return async () => {
        if (navigator && navigator.clipboard) {
            try {
                let message = "snackbars.copied-blocks";
                if (elementType === "block") {
                    message = cutMode ? "snackbars.cut-block" : "snackbars.copied-block";
                }
                await copyElement(block, elementType, cutMode);
                snackbar(t(message), "success");
            }
            catch (e) {
                if (isLocalhost()) {
                    console.info("writing into clipboard error", e);
                }
                snackbar(t("snackbars.copy-error"), "error");
            }
        }
        else {
            clipboardError();
        }
    };
}
export async function copyDates(block) {
    const { dates } = block.element.dataset;
    if (dates) {
        window.sessionStorage.setItem("copiedDates", dates);
        snackbar(t("snackbars.copied-dates"), "success");
    }
    else {
        snackbar(t("snackbars.no-data-to-copy"), "warning");
    }
}
export function setOrUpdateUuids(block) {
    if (!block.editor?.withUuid) {
        return;
    }
    const blocks = Array.from(block.editor.element.querySelectorAll("section[data-template]")).reverse();
    blocks.forEach((currentBlock) => {
        const currentUuid = currentBlock.dataset.uuid;
        const isDuplicate = blocks.filter((candidate) => candidate !== currentBlock && candidate.dataset.uuid === currentUuid).length > 0;
        if (isDuplicate || !currentUuid) {
            const uuid = buildUuid();
            currentBlock.dataset.uuid = uuid;
        }
    });
}
export async function pasteAtPosition(block, position) {
    if (!block.editor) {
        return;
    }
    await pasteFromClipboard(position, block.element);
    setOrUpdateUuids(block);
    block.editor.desactivate();
    await block.editor.analyse();
    block.editor.activate();
    fireEvent(document, EdenEvents.blockPasted, {
        block,
        editor: block.editor,
    });
}
export function createManualPasteAction(block, position) {
    return async () => {
        if (navigator && navigator.clipboard) {
            try {
                await pasteAtPosition(block, position);
                snackbar(t("snackbars.pasted-content"), "success");
            }
            catch (e) {
                if (isLocalhost()) {
                    console.info("Reading from clipboard error", e);
                }
                snackbar(t("snackbars.paste-error"), "error");
            }
        }
        else {
            clipboardError();
        }
    };
}
export async function duplicateBlock(block) {
    if (navigator && navigator.clipboard) {
        await copyElement(block, "block");
        await pasteAtPosition(block, "beforebegin");
    }
    else {
        clipboardError();
    }
}
function cleanupClipboardData(data) {
    return data.replace(/&nbsp;/g, "").replace(/(?:\r\n|\r|\n)/g, "<br />");
}
export function handleBlockPaste(e) {
    e.stopPropagation();
    e.preventDefault();
    const { clipboardData } = e || window;
    if (!clipboardData) {
        return;
    }
    const pastedData = cleanupClipboardData(clipboardData.getData("text/plain"));
    document.execCommand("insertHTML", false, pastedData);
}
export async function pasteFromClipboard(position, elementRef) {
    const clipboardContent = await navigator.clipboard.readText();
    if (clipboardContent.startsWith("fromEden:")) {
        const content = clipboardContent.replace("fromEden:", "");
        elementRef.insertAdjacentHTML(position, content);
    }
    const newElement = {
        beforebegin: elementRef.previousElementSibling,
        afterbegin: elementRef.firstChild,
        afterend: elementRef.nextElementSibling,
    };
    smoothScrollTo(newElement[position]);
}
export function clipboardError() {
    document.body.appendChild(new EdenModal({
        title: t("snackbars.config-error-title"),
        content: t("snackbars.clipboard-config-error"),
    }));
}
