// test is located in test/extract-mentions

import * as mfm from "mfm-js";

export function extractMentions(
	nodes: mfm.MfmNode[],
): mfm.MfmMention["props"][] {
	const mentions: mfm.MfmMention["props"][] = [];

	collectMentions(nodes, mentions);

	return mentions;
}

function collectMentions(
	nodes: mfm.MfmNode[],
	mentions: mfm.MfmMention["props"][],
): void {
	for (let i = 0; i < nodes.length; i++) {
		const node = nodes[i];

		if (node.type === "mention" && !isWrappedUserEmojiMention(nodes, i)) {
			mentions.push(node.props);
		}

		if ("children" in node && Array.isArray(node.children)) {
			collectMentions(node.children, mentions);
		}
	}
}

function isWrappedUserEmojiMention(nodes: mfm.MfmNode[], index: number): boolean {
	const previous = nodes[index - 1];
	const next = nodes[index + 1];

	return (
		previous?.type === "text" &&
		next?.type === "text" &&
		previous.props.text.endsWith(":") &&
		next.props.text.startsWith(":")
	);
}
