import _ from 'lodash';
import { Node } from 'unist';
import { visitParents } from 'unist-util-visit-parents'


const emojiPlugin = (emojiFileNames: string[]) => () => {
  const visitor = (node: any, ancestors: any[]) => {
    const parent = _.last(ancestors);
    const nodeIndex = parent?.children.indexOf(node);

    const text: string = node.value;

    const match = text?.match(/(:.*?:)/);

    if (match && match.index !== undefined) {
      const emoji = match[0]?.replaceAll(':', '') || '';
      const src = emojiFileNames.find(fileName => fileName.match(`${emoji}.*`));

      const beforeNode = {
        type: 'text',
        value: text.slice(0, match.index),
      }

      const emojiNode = {
        type: 'element',
        tagName: 'emoji',
        children: [{
          type: 'text',
          value: src,
        }],
      }

      const afterNode = {
        type: 'text',
        value: text.slice(match.index + emoji?.length + 2),
      }

      parent.children.splice(nodeIndex, 1, ...[beforeNode, emojiNode, afterNode])
    }

  }

  return (tree: Node) => {
    visitParents(tree, { type: 'text' }, visitor);
  }
}

export default emojiPlugin;
