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

export default function splitLyrics(
  alignedLyrics: AlignedLyric[],
  startSeconds: number,
  endSeconds: number,
  preBlankToMiddle: boolean = false,
  postBlankToMiddle: boolean = false
): [AlignedLyric[], AlignedLyric[], AlignedLyric[]] {
  const preSelection: AlignedLyric[] = [];
  const selection: AlignedLyric[] = [];
  const postSelection: AlignedLyric[] = [];

  let seenSelection = false;
  let inSelection = false;
  for (let i = 0; i < alignedLyrics.length; i++) {
    const lyric = alignedLyrics[i];
    const lyricStartSeconds = getLyricStartSeconds(lyric);
    const lyricEndSeconds = getLyricEndSeconds(lyric);
    const lyricMiddleSeconds = (lyricStartSeconds + lyricEndSeconds) / 2;
    if (
      lyric.timing &&
      (lyricMiddleSeconds > startSeconds || lyricStartSeconds === startSeconds)
    ) {
      inSelection = true;
      seenSelection = true;
    }
    if (
      inSelection &&
      lyric.timing &&
      (lyricMiddleSeconds > endSeconds ||
        (lyricStartSeconds === endSeconds && lyricEndSeconds > endSeconds))
    ) {
      inSelection = false;
    }
    if (!inSelection && !seenSelection) {
      preSelection.push(lyric);
    } else if (inSelection) {
      selection.push(lyric);
    } else {
      postSelection.push(lyric);
    }
  }

  // at this point, selection will contain blank-timed lyrics at the end, but not at the start.
  if (!postBlankToMiddle) {
    while (
      selection.length > 0 &&
      !selection[selection.length - 1].timing &&
      !selection[selection.length - 1].text.trim()
    ) {
      postSelection.unshift(selection.pop()!);
    }
  }

  if (preBlankToMiddle) {
    while (
      preSelection.length > 0 &&
      !preSelection[preSelection.length - 1].timing &&
      !preSelection[preSelection.length - 1].text.trim()
    ) {
      selection.unshift(preSelection.pop()!);
    }
  }

  return [preSelection, selection, postSelection];
}
