import { $createRangeSelection, $getRoot, TextPoint } from 'lexical';

export default function $splitTextContent(...points: TextPoint[]): string[] {
  const root = $getRoot();
  if (points.length === 0) return [root.getTextContent()];
  const allTextNodes = root.getAllTextNodes();
  let prevNode = allTextNodes[0];
  if (!prevNode) return [root.getTextContent()];
  let prevOffset = 0;
  const strings = [];

  for (let i = 0; i < points.length; i++) {
    const node = points[i].getNode();
    const offset = points[i].offset;
    if (!node) throw new Error('Invalid point');
    const selection = $createRangeSelection();
    selection.anchor.set(prevNode.getKey(), prevOffset, 'text');
    selection.focus.set(node.getKey(), offset, 'text');
    prevNode = node;
    prevOffset = offset;
    strings.push(selection.getTextContent());
  }
  const lastTextNode = allTextNodes.slice(-1)[0];
  const selection = $createRangeSelection();
  selection.anchor.set(prevNode.getKey(), prevOffset, 'text');
  selection.focus.set(
    lastTextNode.getKey(),
    lastTextNode.getTextContentSize(),
    'text'
  );
  strings.push(selection.getTextContent());
  return strings;
}
