 _ = require 'underscore'
+
 # XRegExp = require('xregexp').XRegExp
 WordRegExp = /\S+\s*/g
 PreSpacesRegExp = /^\s+/
+PostSpacesRegExp = /\s+$/
 # Simple class that contains a word and links to the selections pointing
 # to it
 class Word

  #
  insertWords: (position, words)->
    # TODO: update selections
    if typeof position isnt "number"
      throw new Error 'Expected a number as first parameter'
    if words.constructor isnt Array
      throw new Error 'Expected a string array as second parameter'
    if 0 <= position <= @_rte.words.length
      after = [new Word ' '].concat(@getWords(position))
      before = @getWords(0, Math.max(position-1, 0)).append(new Word ' ')
      if position == 0
        before = []
      else
        before = @_rte.words[..position-1]
      after = @_rte.words[position..]
      @_rte.words = before.concat(words).concat(after)
      # @updateInsertWords(position, words.length)
    else
      throw new Error 'Index #{position} out of bound in word list'


  # Append new words at the end of the word list
  # @param [String] content the string to append
  push: (content) ->
    preSpaces = content.match PreSpacesRegExp
    if preSpaces isnt null
      @_rte.words.push(new Word (preSpaces[0]))
    words = content.match WordRegExp
    if _.isArray(words)
      for w in words
        @_rte.words.push (new Word w)
