import { LexicalNode } from 'lexical';

import AlignedLyricNode from './AlignedLyricNode';
import {
  getLyricEndSeconds,
  getLyricStartSeconds,
} from './refineAlignedLyrics';

export default function getNodeTimeSpan(
  node: LexicalNode
): [number | null, number | null] {
  let timingStartSeconds = null;
  let timingEndSeconds = null;
  let prevNode = node.getPreviousSibling();
  if (prevNode instanceof AlignedLyricNode) {
    timingStartSeconds = prevNode.alignedLyric.timing
      ? getLyricEndSeconds(prevNode.alignedLyric)
      : null;
  }
  while (timingStartSeconds === null && !!prevNode) {
    prevNode = prevNode.getPreviousSibling();
    if (prevNode instanceof AlignedLyricNode && prevNode.alignedLyric.timing) {
      timingStartSeconds = getLyricEndSeconds(prevNode.alignedLyric);
    }
  }

  let nextNode = node.getNextSibling();
  if (nextNode instanceof AlignedLyricNode) {
    timingEndSeconds = nextNode.alignedLyric.timing
      ? getLyricStartSeconds(nextNode.alignedLyric)
      : null;
  }
  while (timingEndSeconds === null && !!nextNode) {
    nextNode = nextNode.getNextSibling();
    if (nextNode instanceof AlignedLyricNode && nextNode.alignedLyric.timing) {
      timingEndSeconds = getLyricStartSeconds(nextNode.alignedLyric);
    }
  }
  return [timingStartSeconds, timingEndSeconds] as const;
}
