var util = require('util');
var Device = require('zetta-device');

var WemoInsight = module.exports = function(device, client) {
  this.name = device.friendlyName;
  this.state = 'off';
  this.power = 0;
  this.UDN = device.UDN;
  this._client = client;
  Device.call(this);
};
util.inherits(WemoInsight, Device);

WemoInsight.prototype.init = function(config) {
  config
    .type('wemo-insight')
    .state(this.state)
    .name(this.name)
    .monitor('power')
    .when('off', { allow: ['turn-on'] })
    .when('on', { allow: ['turn-off'] })
    .when('standby', { allow: ['turn-off'] })
    .map('turn-on', this.turnOn)
    .map('turn-off', this.turnOff);

  this._client.on('binaryState', function(value){
    var states = {
      1: 'on',
      0: 'off',
      8: 'standby'
    };
    this.state = states[value];

    // Reset power value if device goes off
    if (this.state == 'off') {
      this.power = 0;
    }
  }.bind(this));

  this._client.on('insightParams', function(state, power) {
    this.power = Math.round(power / 1000);
  }.bind(this));
};

WemoInsight.prototype.turnOn = function(cb) {
  this._client.setBinaryState(1);
  this.state = 'on';
  cb();
};

WemoInsight.prototype.turnOff = function(cb) {
  this._client.setBinaryState(0);
  this.state = 'off';
  cb();
};

@@ -308,16 +308,88 @@
 vice);%0A%0A
+WemoInsight.BINARY_STATES = %7B%0A  1: 'on',%0A  0: 'off',%0A  8: 'standby'%0A%7D;%0A%0A
 WemoInsi
@@ -759,16 +759,177 @@
 yState',
+ this._binaryStateHandler.bind(this));%0A  this._client.on('insightParams', this._insightParamsHandler.bind(this));%0A%7D;%0A%0AWemoInsight.prototype._binaryStateHandler =
  functio
@@ -937,15 +937,12 @@
 (val
-ue)%7B%0A  
+) %7B%0A
   va
@@ -952,70 +952,72 @@
 tate
-s
  = 
-%7B%0A      1: 'on',%0A      0: 'off',%0A      8: 'standby'%0A    %7D;
+WemoInsight.BINARY_STATES%5Bval%5D;%0A  if (this.state !== state) %7B
 %0A   
@@ -1039,21 +1039,15 @@
 tate
-s%5Bvalue%5D
 ;%0A
-%0A
   
+%7D%0A%0A
   //
@@ -1088,21 +1088,14 @@
 off%0A
-  
   if (
-this.
 stat
@@ -1112,18 +1112,16 @@
 ) %7B%0A    
- 
- 
 this.pow
@@ -1134,49 +1134,37 @@
 ;%0A  
-  %7D%0A  %7D.bind(this));%0A%0A  this._client.on('
+%7D%0A%7D;%0A%0AWemoInsight.prototype._
 insi
@@ -1172,18 +1172,25 @@
 htParams
-',
+Handler =
  functio
@@ -1191,21 +1191,19 @@
 unction(
-state
+val
 , power)
@@ -1201,26 +1201,24 @@
 l, power) %7B%0A
-  
   this.power
@@ -1250,25 +1250,8 @@
 0);%0A
-  %7D.bind(this));%0A
 %7D;%0A%0A
@@ -1334,29 +1334,8 @@
 1);%0A
-  this.state = 'on';%0A
   cb
@@ -1423,38 +1423,16 @@
 ate(0);%0A
-  this.state = 'off';%0A
   cb();%0A

Improve state handling for wemo-insight