var _ = require('lodash')
var transform = require('./transform.js')

function Automove(data) {
  if (!data) data = {}
  this.speed = data.speed || {position: 1, angle: 10}
  this.keymap = data.keymap || ['Q', 'W', 'E', 'A', 'S', 'D']
  this.heading = data.heading || [-60, 0, 60, -120, -180, 120]
  this.shift = data.shift || 1
  this.active = [false, false, false, false, false, false]
  this.target = 0
}

Automove.prototype.compute = function(keys, current, offset) {
  var self = this

  if (!offset) offset = current

  self.keymap.forEach( function(key, i) {
    if (key in keys & !(_.any(self.active))) {
      self.active[i] = true
      self.target = self.totarget(current, self.heading[i], offset)
    }
  })

  if (self.target) {
    var dist = current.distance(self.target)
    if (!(dist.position || dist.angle)) self.target = 0
  }

  var pressed = self.keymap.map(function (k) {return k in keys})
  if (!_.any(pressed)) self.reset()

  if (!self.target) return self.delta(current, self.totarget(current, 0, current))

  return self.delta(current, self.target)
}

Automove.prototype.totarget = function (current, heading, offset) {
  return {
    position: [
      this.shift * Math.sin((current.angle() + heading) * Math.PI / 180) + offset.position()[0], 
      this.shift * -Math.cos((current.angle() + heading) * Math.PI / 180) + offset.position()[1]
    ], 
    angle: current.angle() + heading
  }
}

Automove.prototype.reset = function() {
  var self = this
  self.keymap.forEach(function (k, i) {
    self.active[i] = false
  })
}

Automove.prototype.delta = function(current, target) {
  var dist = current.distance(target)

  var speed = this.speed
  var velocity = {position: 1, angle: 1}
  var diff = current.difference(target)

  if (dist.position > speed.position) {
    diff.position[0] = diff.position[0] / dist.position
    diff.position[1] = diff.position[1] / dist.position
    velocity.position = speed.position
    if (dist.angle > speed.angle) velocity.position = speed.angle * dist.position / dist.angle
  }

  if (dist.angle > speed.angle) {
    diff.angle = diff.angle / dist.angle
    velocity.angle = speed.angle
  }

  return {
    position: [
      diff.position[0] * velocity.position, 
      diff.position[1] * velocity.position
    ], 
    angle: diff.angle * velocity.angle
  }
}

module.exports = Automove
@@ -388,25 +388,31 @@
   this.t
-arget = 0
+racking = false
 %0A%7D%0A%0AAuto
@@ -660,32 +660,28 @@
 rget = self.
-totarget
+seek
 (current, se
@@ -699,24 +699,51 @@
 i%5D, offset)%0A
+      self.tracking = true%0A
     %7D%0A  %7D)%0A%0A
@@ -754,21 +754,23 @@
  (self.t
-arget
+racking
 ) %7B%0A    
@@ -860,17 +860,83 @@
 lf.t
-arget = 0
+racking = false%0A  %7D else %7B%0A    self.target = self.seek(current, 0, current)
 %0A  %7D
@@ -1043,92 +1043,8 @@
 ()%0A%0A
-  if (!self.target) return self.delta(current, self.totarget(current, 0, current))%0A%0A
   re
@@ -1107,16 +1107,12 @@
 ype.
-totarget
+seek
  = f

Introduce tracking boolean