/**
 * Returns an object containing the segmented text and metainfo about word and
 * sentence beginnings
 * @param {String} text
 * @param {Number} maxLength
 * @returns {Object}
 */
export function parseText(text, maxLength) {
  let segments = []
  let words = []
  let sentences = []
  let curIdx = 0
  let sentenceFlag = true

  for (let word of extractWords(text)) {
    // fill metainfo
    words.push(curIdx)
    if (sentenceFlag) {
      sentences.push(curIdx)
    }
    // fragmentize word if necessary and fill segments
    let fragments = splitLongWord(word, maxLength)
    segments.push(...fragments)
    curIdx += fragments.length

    // set flag if next word is sentence beginning
    sentenceFlag = word.endsWith('.')
  }

  return { segments, words, sentences }
}

/**
 * Returns an Array words from a text. Words are identified by whitespace.
 * @param {String} text
 * @returns {Array<String>}
 */
function extractWords(text) {
  let words = []
  for (let word of text.trim().split(/[ \t\n]/)) {
    if (word.trim() !== '') {
      words.push(word)
    }
  }
  return words
}

/**
 * Splits a word evenly in parts with maximum length of maxLength.
 * Todo: more intelligent hyphenation algorithm
 * @param {String} word
 * @param {Number} maxLength
 * @returns {Array<String>} word fragents
 */
function splitLongWord(word, maxLength = -1) {
  if (maxLength === -1) return [word]
  if (maxLength === word.length) return [word]

  let fragments = []
  let numParts = Math.floor(word.length / maxLength) + 1
  let step = word.length / numParts
  let start = 0
  let end = step

  while (start < word.length) {
    fragments.push(word.slice(start, end))
    start += step
    end += step
  }
  for (let i = 0; i < fragments.length - 1; i++) {
    fragments[i] = fragments[i] + '-'
  }
  return fragments
}

export const _privates = { extractWords, splitLongWord }
