'use strict'

let typingMechanics = require('./typingMechanics')
const timer = require('./timer')
const lev = require('./vendor/fast-levenshtein')

module.exports = {
  texts: null,
  loadText: function loadText (textObj) {
    typingMechanics.textObj = textObj
    $('.text').show().val(textObj.text).fixHeight()
    $('.go').removeAttr('disabled').show()

    // remove any existing typing data
    timer.resetTimer()
  },
  /**
   * populate the list with Texts. Runs once on page load.
   */
  initLoad: function initLoad () {
    var userTexts = $('#user-texts').find('ul').empty() // DOM el

    this.texts = JSON.parse(window.localStorage.getItem('texts')) // an array of textObjects

    if (this.texts === undefined) {
      return
    }
    this.texts.forEach(function (el) {
      var li = $('<li><span class="text-title">' + el.title +
        '</span><span class="glyphicon glyphicon-cog text-menu" data-toggle="modal" data-target="#text-edit" data-text-id="' + el.id + '"></span></li>') // TODO use Polymer element here
      li.data('text', el.text)
      li.data('id', el.id)
      userTexts.append(li)
      li.on('click', 'span.text-title', function () {
        module.exports.loadText(el)
      })
    })
  },
  saveText: function saveText (textObj) {
    // do some validation first. Is this textObj already there? if so, update.
    this.texts.push(textObj)
    this.persistTexts()
    module.exports.loadText(textObj)
  },
  editText: function editText (textId, newTitle, newText) {
    var textObj = this.getByTextId(textId)
    var distance = lev.get(textObj.text.toLowerCase(), newText.toLowerCase())

    if (distance > 30) { // an arbitrary number
      // AND there is historical data for this text
      // TODO display warning text saying that historical data may become very inaccurate. Is that even true?
      console.log('Text ' + textObj.id + ' has been changed significantly.')
    }

    textObj.text = newText
    textObj.title = newTitle
    this.persistTexts()

    // update .text if this text is loaded in it
    if (typingMechanics.textObj !== undefined && typingMechanics.textObj.id === textId) {
      $('textarea.text').val(newText)
    }
  },
  deleteText: function deleteText (textId) {
    this.texts = this.texts.filter(function (el) {
      return el.id !== textId
    })
    this.persistTexts()

    // clear .text if this text is loaded in it
    if (typingMechanics.textObj !== undefined && typingMechanics.textObj.id === textId) {
      $('textarea.text').val('')
      $('#text-edit').removeData('textId')
      $('.go').attr('disabled', 'disabled')
    }
  },
  persistTexts: function persistTexts () {
    window.localStorage.setItem('texts', JSON.stringify(this.texts))
  },

  getByTextId: function getByTextId (textId) {
    var textObjArray = this.texts.filter(function filterById (textObj) {
      return textObj.id === textId
    })
    if (textObjArray.length !== 1) {
      console.log('Searched for textId ' + textId + ' but did not find a unique result. Full texts: \n' + this.texts) // TODO replace with a real logging implementation
      throw new Error('Unique result not found')
    }
    return textObjArray[0]
  }
}

@@ -144,285 +144,112 @@
 n')%0A
-%0Amodule.exports = %7B%0A  texts: null,%0A  loadText: function loadText (textObj) %7B%0A    typingMechanics.textObj = textObj%0A    $
+let texts = JSON.parse(window.localStorage.getItem
 ('
-.
 text
+s
 ')
-.show().val(textObj.text).fixHeight()%0A    $('.go').removeAttr('disabled').show()%0A%0A    // remove any existing typing data%0A    timer.resetTimer()%0A  %7D,
+) // an array of textObjs%0A%0Amodule.exports = %7B
 %0A  /
@@ -359,16 +359,17 @@
     var 
+$
 userText
@@ -427,130 +427,25 @@
     
-this.texts = JSON.parse(window.localStorage.getItem('texts')) // an array of textObjects%0A%0A    if (this.texts === undefined
+if (texts == null
 ) %7B%0A
@@ -463,29 +463,24 @@
 n%0A    %7D%0A    
-this.
 texts.forEac
@@ -809,16 +809,17 @@
 )%0A      
+$
 userText
@@ -942,16 +942,259 @@
 %7D)%0A  %7D,%0A
+  loadText: function loadText (textObj) %7B%0A    typingMechanics.textObj = textObj%0A    $('.text').show().val(textObj.text).fixHeight()%0A    $('.go').removeAttr('disabled').show()%0A%0A    // remove any existing typing data%0A    timer.resetTimer()%0A  %7D,%0A
   saveTe
@@ -1306,29 +1306,72 @@
 update.%0A    
-this.
+if (texts == null) %7B%0A      texts = %5B%5D%0A    %7D%0A    
 texts.push(t
@@ -2242,21 +2242,16 @@
     
-this.
 texts = 
 this
@@ -2246,21 +2246,16 @@
 texts = 
-this.
 texts.fi
@@ -2705,21 +2705,16 @@
 ringify(
-this.
 texts))%0A
@@ -2789,21 +2789,16 @@
 Array = 
-this.
 texts.fi
@@ -3019,21 +3019,16 @@
 : %5Cn' + 
-this.
 texts) /

Fix bug when there's no 'texts' in localStorage