/**
 * This is pretty much a direct copy from:
 * https://github.com/CrystallizeAPI/crystallize-content-transformer/blob/main/src/converters/text/to-text.js
 * I could not/did not want to import it since then original package is not in Typescript
 */

import type { CrystallizeRichText, CrystallizeRichTextNode } from '../types/crystallize-rich-text-types';

// Remove first and last new lines
function trim(str: string) {
  if (!str) {
    return '';
  }

  return str.replace(/^(\r|\n)+/, '').replace(/(\r|\n)+$/, '');
}

export function toText(model: CrystallizeRichText, options?: { keepLineBreaks: boolean }) {
  function getTextFromNode(node: CrystallizeRichTextNode) {
    if (!node) {
      return '';
    }

    let childrenText = '';
    if (node.children) {
      childrenText = node.children.reduce((acc, n) => acc + getTextFromNode(n), '');
    }

    let content = '';

    content += node.textContent || childrenText || '';

    if (node.kind === 'block') {
      content = `\n${content}\n`;
    } else if (options?.keepLineBreaks && node.type === 'line-break') {
      content += '\n';
    }

    return content;
  }

  if (Array.isArray(model)) {
    return model.map(getTextFromNode).join('').trimStart().trimEnd();
  }

  return trim(getTextFromNode(model));
}
