import t from "../i18n/index.js";
import { closeDetailsElements, cleanupTagsAndPreserveContent, randomizeSvgSpriteCalls, cleanupRandomSvgSpriteCallParams, } from "../services/cleanup.js";
import { saveEditors } from "../services/api.js";
import { EdenEvents, fireEvent } from "../services/event.js";
import { getRuntimeConfig } from "../services/runtime.js";
import { fetchTimestamp } from "../services/fetcher.js";
import { snackbar } from "../user-interface/common/eden-snackbar.js";
export async function refreshEdenTimestamp(eden) {
    const { timestamp } = await fetchTimestamp();
    eden.startedAt = timestamp;
}
export async function saveEden(eden) {
    eden.desactivate();
    eden.preSave();
    eden.cleanMarkup();
    const { lang } = getRuntimeConfig();
    const pathname = window.location.pathname;
    const { error } = await saveEditors({
        lang,
        path: pathname,
        startedAt: eden.startedAt,
    });
    eden.postSave(error);
}
export function postSaveEden(eden, error) {
    if (error) {
        return snackbar(error, "error");
    }
    eden.editors.map((editor) => editor.postSave());
    fireEvent(document, EdenEvents.contentSaved);
    snackbar(t("snackbars.content-saved"), "success");
    randomizeSvgSpriteCalls();
    setTimeout(() => {
        eden.startedAt = Date.now();
    }, 100);
}
export function cleanEdenMarkup() {
    const selectorsToRemove = [
        "grammarly-extension",
        "lt-highlighter",
        "eden-editor-ui",
        "eden-editor-ui",
        "eden-info-ui",
        "eden-block-ui",
        "[data-dashlanecreated]",
        "mci-extension",
        "editor-squiggler",
        '[class="monica-widget"]',
    ];
    const elementsToRemove = Array.from(document.querySelectorAll(selectorsToRemove.join()));
    elementsToRemove.forEach((el) => el.remove());
    const attributesToRemove = [
        "spellcheck",
        "data-lt-tmp-id",
        "data-gramm",
        "data-eden-helper",
        "data-dashlane-rid",
        "data-form-type",
        "data-kwimpalastatus",
        "data-mci-spellchecked",
        "data-full-weeks-obsolete",
        "data-ms-editor",
    ];
    attributesToRemove.forEach((attribute) => {
        const targets = Array.from(document.querySelectorAll(`[${attribute}]`));
        targets.forEach((target) => target.removeAttribute(attribute));
    });
    const classNamesToRemove = ["undefined"];
    classNamesToRemove.forEach((className) => {
        const targets = Array.from(document.querySelectorAll(`.${className}`));
        targets.forEach((target) => target.classList.remove(className));
    });
    cleanupTagsAndPreserveContent("font[style], tcxspan");
    closeDetailsElements();
    cleanupRandomSvgSpriteCallParams();
}
