"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.moveLinkToQuoteAttributes = void 0;
const utils_1 = require("./utils.js");
const __1 = require("../index.js");
const moveLinkToQuoteAttributes = (md) => {
    md.core.ruler.push('move-link-to-quote-attributes', (state) => {
        const { tokens } = state;
        let i = 0;
        while (i < tokens.length) {
            const token = tokens[i];
            if (token.type === 'yfm_quote-link_open') {
                const inlineToken = tokens[i + 2];
                const linkMatch = (0, utils_1.matchLinkAtInlineStart)(inlineToken);
                if (linkMatch?.openToken.attrIndex('data-quotelink') !== -1 &&
                    linkMatch?.closeTokenIndex) {
                    token.attrSet(__1.QuoteLinkAttr.Cite, linkMatch?.openToken.attrGet('href') ?? '');
                    const content = inlineToken.children
                        ?.slice(1, linkMatch.closeTokenIndex)
                        .reduce((result, item) => result + item.content, '')
                        .trim();
                    if (content) {
                        token.attrSet(__1.QuoteLinkAttr.DataContent, content);
                    }
                    if (linkMatch.closeTokenIndex === (inlineToken.children?.length ?? 0) - 1) {
                        tokens.splice(i + 1, 3);
                    }
                    else {
                        inlineToken.children?.splice(0, linkMatch.closeTokenIndex + 1);
                        if (inlineToken.children?.every((childToken) => !childToken.content)) {
                            tokens.splice(i + 1, 3);
                        }
                    }
                }
            }
            i++;
        }
    });
};
exports.moveLinkToQuoteAttributes = moveLinkToQuoteAttributes;
//# sourceMappingURL=moveLinkToQuoteAttributes.js.map
