import type { Controller } from "../../controller";
import { PID } from "../../persist";
import { Point, Range } from "../../editor";

export function getEffectKeys(pids: PID[], range: Range): PID[] {
  const { start, end } = range;
  const startPos = pids.indexOf(start.pid);
  const endPos = pids.indexOf(end.pid);
  if (endPos === -1 || endPos === -1) {
    // error
    return [];
  }
  return pids.slice(startPos, endPos + 1);
}

export function getParagraphRanges(controller: Controller, range: Range) {
  const pids = controller.getPids();
  const effectKeys = getEffectKeys(pids, range);
  const { start, end } = range;
  const paragraphRanges = new Map<PID, Range>();

  effectKeys.forEach(pid => {
    const isStart = pid === start.pid;
    const isEnd = pid === end.pid;

    const startOffset = isStart ? start.offset : 0;
    const endOffset = isEnd ? end.offset : controller.getTextContent(pid).length;

    const newRange = Range.create({
      start: Point.create(pid, startOffset),
      end: Point.create(pid, endOffset),
    });

    paragraphRanges.set(pid, newRange);
  });
  return paragraphRanges;
}
