




(function () {
  'use strict';

  var TWEEN_MS = 400;      

  function Twin(robot) {
    this.robot = robot;
    this.current = null;    
    this._from = null;
    this._to = null;
    this._t0 = 0;
    this._dur = 0;
  }

  Twin.prototype.snapTo = function (deg) {
    this.current = deg.slice();
    this._to = null;
    this.robot.setJointsDeg(this.current);
  };

  
  Twin.prototype.sample = function (deg) {
    if (!this.current) { this.snapTo(deg); return; }
    this._from = this.current.slice();
    this._to = deg.slice();
    this._t0 = performance.now();
    this._dur = TWEEN_MS;
  };

  



















  Twin.prototype.live = function (deg) {
    this.snapTo(deg);
  };

  
  Twin.prototype.animateTo = function (deg, durationS) {
    if (!this.current) { this.snapTo(deg); return; }
    this._from = this.current.slice();
    this._to = deg.slice();
    this._t0 = performance.now();
    this._dur = Math.max(durationS * 1000, TWEEN_MS);
  };

  






  Twin.prototype.update = function (now) {
    if (!this._to) return;
    var k = (performance.now() - this._t0) / this._dur;
    if (k <= 0) { this.robot.setJointsDeg(this.current); return; }
    if (k >= 1) {
      this.current = this._to.slice();
      this._to = null;
    } else {
      for (var i = 0; i < 6; i++) {
        this.current[i] = this._from[i] + (this._to[i] - this._from[i]) * k;
      }
    }
    this.robot.setJointsDeg(this.current);
  };

  window.Twin = Twin;
})();
