var asyncMap = require('slide').asyncMap
var through = require('through2') // fix this thing up!
var utils = require('utils')
var domify = require('domify')

module.exports = function Actions (C) {
  var omnibox
  var status
  var menu
  var search

  var omni = {
    _ : null,
    live : false,
    next : function () {
      console.log('next!')
    },
    prev : function () {
      console.log('prev!')
    },
    go : function () {
      if (typeof this._ === 'object' && this._.nimoy) {
        var pkg = this._
        s.push({key:'draw', value: pkg})
      }
    }
  }

  var s = through.obj(function Write (chunk, enc, next) { 
    console.log(enc)
    console.log(chunk)
    next()
  })

  if (localStorage.library && localStorage.library.length > 0) {
    var library = JSON.parse(localStorage.library)
  } else library = null // request library

  window.addEventListener('contextmenu', ctx, false)

  window.addEventListener('keydown', function toggleOmni (e) {
    if (e.keyCode === 38) { omni.live = false; search.focus() }
    if (e.keyCode === 37) omni.prev()
    if (e.keyCode === 39) omni.next()
    if (C.live && omni.live === true && e.keyCode === 13) omni.go()
    if (e.keyCode === 27 ) { // keybindings!
      e.preventDefault();
      (C.live === false) ? C.draw() : C.erase()
      return false
    }
  }, false) 

  function ctx (e) {
    e.preventDefault()
    var element = e.target
    var id = element.id
    var parent = element.parentElement // ?
    var cl = element.className
    var tag = element.tagName
    console.log(element, parent, parent.id, tag, cl)
  }

  function updateSearch (e) {
    e.preventDefault()
    omnibox.innerHTML = ''
    var str = search.value
    var res = utils.search(library, str) 

    if (res) {// preview res
      omni._ = res
      omnibox.innerHTML = res.name
    } else omni._ = null

    if (e.keyCode===40||e.keyCode===39||e.keyCode===13||e.keyCode===9) {
      console.log(e.keyCode)
      e.preventDefault()
      search.blur()
      omni.live = true
    }
  }

  function processResult (d) {
    if (typeof d === 'object') {
      if (d.nimoy) {
        console.log('its a package!')
      }
    }
  }

  function newMsg (id, msg) {
    return domify('<li id="' + id + '">' + msg + '</li>')
  }
    
  function fileUpload (e) {
    e.preventDefault()

    var files = []
    var droppedFiles = e.dataTransfer.files

    for (var i=0; i<droppedFiles.length; i++) {
      var f = droppedFiles[i]
      if (f.type.match('image.*')) files.push(f)
    }

    asyncMap(files, function handleFile (file, next) {
      var fileName = file.name
      var cleanName = file.name.replace(/ /g,'_')
      var id = utils.UID(cleanName)

      var formData = new FormData()
      formData.append('file', cleanName)
      formData.append('token', 'test123') // !?

      var xhr = new XMLHttpRequest()
      xhr.upload.addEventListener('error', function (e) {
        console.error(e)
      }, false) 
      xhr.upload.addEventListener('loadend', function (e) {
        console.log(e)
      }, false) 
      xhr.upload.addEventListener('progress', function (e) { 
        console.log(e)
        var percent = (e.loaded / e.total)*100
        var msg = newMsg(id, 'uploading :'+cleanName+' '+percent+'%')
        messages.appendChild(msg)
        if (e.loaded === e.total) {
          setTimeout(function () {
            messages.removeChild(document.getElementById(id))
          }, 1000)
        }
      }, false) 
      xhr.open('post', '/upload', true) 

      var reader = new FileReader()
      reader.addEventListener('load', function (data) {
        console.log(data.target.result)
        formData.append('blob', data.target.result)
        console.log(formData)
        xhr.send(formData)
      }, false)
      reader.readAsDataURL(file)
    }, function End () {
      console.dir(droppedFiles)
    })
  }
    
  function cancel (e) {
    e.preventDefault()
    if (e.stopPropogation) e.stopPropogation()
    return false
  }

  // logic for processing omni results

  C.onErase = function () {
    console.log('erased')
    search.removeEventListener('keyup', updateSearch)
    omnibox.removeEventListener('drop', fileUpload)
    omnibox.removeEventListener('dragenter', cancel)
    omnibox.removeEventListener('dragover', cancel)
    omnibox.removeEventListener('dragleave', cancel)
  }

  C.onDraw = function (domNode) {
    console.log('draw')
    omnibox = domNode.querySelector('.omnibox')
    messages = domNode.querySelector('.messages')
    omnibox.addEventListener('dragleave', cancel, false)
    omnibox.addEventListener('dragover', cancel, false)
    omnibox.addEventListener('dragenter', cancel, false)
    omnibox.addEventListener('drop', fileUpload, false)
    search = domNode.querySelector('#search')
    search.addEventListener('keyup', updateSearch, false)
    search.focus()
  }

  return s
}

@@ -2693,16 +2693,100 @@
 eanName)
+%0A      var msg = newMsg(id, 'uploading :'+cleanName)%0A      messages.appendChild(msg)
 %0A%0A      
@@ -3286,103 +3286,36 @@
     
-var msg = newMsg(id, 'uploading :'+cleanName+' '+percent+'%25')%0A        messages.appendChild(msg)
+msg.innerHTML += ' '+percent
 %0A   

fix adding/removing mssgs to status