export interface CorpusLine {
  readonly text: string;
  readonly ending: string;
}

function lineEndingLength(text: string, index: number): number {
  const code = text.charCodeAt(index);
  if (code === 0x0d) {
    return text.charCodeAt(index + 1) === 0x0a ? 2 : 1;
  }
  return code === 0x0a || code === 0x2028 || code === 0x2029 ? 1 : 0;
}

export function countCorpusLines(text: string): number {
  let count = 1;
  for (let index = 0; index < text.length; index += 1) {
    const endingLength = lineEndingLength(text, index);
    if (endingLength === 0) continue;
    count += 1;
    index += endingLength - 1;
  }
  return count;
}

export function splitCorpusLines(text: string): readonly CorpusLine[] {
  const lines: CorpusLine[] = [];
  let start = 0;
  for (let index = 0; index < text.length; index += 1) {
    const endingLength = lineEndingLength(text, index);
    if (endingLength === 0) continue;
    lines.push({
      text: text.slice(start, index),
      ending: text.slice(index, index + endingLength),
    });
    index += endingLength - 1;
    start = index + 1;
  }
  lines.push({ text: text.slice(start), ending: "" });
  return lines;
}
