import { MarkdownSerializer, defaultMarkdownSerializer, } from "prosemirror-markdown";
import { markdownToHTML } from "../../markdown/markdown-parser";
import { getImageNodeMarkdownSerializer, hasImageNode, } from "../prosemirror-adapter/plugins/image/node";
const createMarkdownSerializerFunction = (config) => {
    return (state, node) => {
        const tagOpen = `<${config.tagName}` +
            config.attributes
                .map((attr) => ` ${attr}="${node.attrs[attr]}"`)
                .join('') +
            '>';
        const tagClose = `</${config.tagName}>`;
        state.write(tagOpen);
        state.renderContent(node);
        state.write(tagClose);
    };
};
const buildMarkdownSerializer = (plugins, language) => {
    const customNodes = {};
    for (const plugin of plugins) {
        customNodes[plugin.tagName] = createMarkdownSerializerFunction(plugin);
    }
    const nodes = Object.assign(Object.assign(Object.assign({}, defaultMarkdownSerializer.nodes), getImageNodeMarkdownSerializer(language)), customNodes);
    const marks = Object.assign(Object.assign({}, defaultMarkdownSerializer.marks), { strikethrough: {
            open: '~~',
            close: '~~',
            mixable: true,
            expelEnclosingWhitespace: true,
        } });
    return new MarkdownSerializer(nodes, marks);
};
/**
 * @private
 */
export class MarkdownConverter {
    constructor(plugins, language) {
        this.parseAsHTML = (text) => {
            return markdownToHTML(text, { whitelist: this.customNodes });
        };
        this.serialize = (view) => {
            if (view.dom.textContent.trim() === '' &&
                !hasImageNode(view.state.doc)) {
                return '';
            }
            return this.markdownSerializer.serialize(view.state.doc);
        };
        this.markdownSerializer = buildMarkdownSerializer(plugins, language);
        this.customNodes = plugins;
    }
}
