import { jsx } from "slate-hyperscript";
import { makeDeserializer } from "./module";
import { imagePastingListener } from "./utils";
/* eslint-disable no-param-reassign */ import { Node } from "slate";
import { EditorUtils } from "..";
var isMarkdownLink = function isMarkdownLink(text) {
    var markdownLinkRegex = /\[([^\]]+)\]\(([^)]+)\)/;
    return markdownLinkRegex.test(text);
};
export var docxDeserializer = function docxDeserializer(rtf, html) {
    var deserialize = makeDeserializer(jsx);
    // image tags have to be cleaned out and converted
    var imageTags = imagePastingListener(rtf, html);
    if (html) {
        var parsed_html = new DOMParser().parseFromString(html, 'text/html');
        var fragmentList = deserialize(parsed_html.body, imageTags || []);
        return fragmentList.filter(function(item) {
            var _item_children_at, _item_children;
            if (item.type === 'paragraph' && !Node.string(item).trim() && !(item === null || item === void 0 ? void 0 : (_item_children = item.children) === null || _item_children === void 0 ? void 0 : (_item_children_at = _item_children.at(0)) === null || _item_children_at === void 0 ? void 0 : _item_children_at.type)) {
                return false;
            }
            return true;
        }).map(function(fragment) {
            if (fragment.type === 'table') {
                return EditorUtils.wrapperCardNode(fragment);
            }
            if (fragment.type === '"paragraph"' && fragment.children.length === 1) {
                return {
                    type: 'paragraph',
                    children: fragment.children
                };
            }
            if (fragment.type === 'head') {
                var _fragment_children_at, _fragment_children;
                if ((fragment === null || fragment === void 0 ? void 0 : (_fragment_children = fragment.children) === null || _fragment_children === void 0 ? void 0 : (_fragment_children_at = _fragment_children.at(0)) === null || _fragment_children_at === void 0 ? void 0 : _fragment_children_at.text) && isMarkdownLink(fragment.children.at(0).text)) {
                    var linkText = fragment.children.at(0).text;
                    fragment.children[0] = {
                        text: linkText === null || linkText === void 0 ? void 0 : linkText.replace(/\[([^\]]+)\]\(([^)]+)\)/, '$1'),
                        url: linkText === null || linkText === void 0 ? void 0 : linkText.replace(/\[([^\]]+)\]\(([^)]+)\)/, '$2'),
                        originalText: linkText
                    };
                }
            }
            return fragment;
        });
    }
    return [];
};
