/* global localStorage, ionic, alert */
angular.module('DeviceSimulator')

.controller('MainCtrl', function ($scope, $state, MQTT) {
  $scope.device = JSON.parse(localStorage.getItem('device'));

  if (!$scope.device) {
    $state.go('tab.associate');
  }

  $scope.connected = false;
  $scope.connecting = true;

  MQTT.connect($scope.device)
    .then(function () {
      $scope.connected = true;
      $scope.syncing = true;
      MQTT.sendMessage('STATUS_REPORT', 'get_status', 'send_status')
        .then(function (message) {
          $scope.device = message.data;
          localStorage.setItem('device', JSON.stringify(message.data));

          $scope.synced = new Date();
        })
        .finally(function () {
          $scope.syncing = false;
        });
    }, function () {
      console.log('Error trying to connect');
    })
    .finally(function () {
      $scope.connecting = false;
    });
})

.controller('HomeCtrl', function ($scope, $state, MQTT) {
  $scope.consumeShot = function () {
    sendMessage('STATUS_REPORT', 'consume_shot')
      .then(function () {
        $scope.device.consumedShots++;
      });
  };

  $scope.refill = function () {
    sendMessage('STATUS_REPORT', 'refill')
      .then(function () {
        $scope.device.consumedShots = 0;
      });
  };

  function sendMessage (dstChannel, type, responseType, data) {
    $scope.sending = true;
    $scope.sendingError = false;

    return MQTT.sendMessage(dstChannel, type, responseType, data)
      .then(function (message) {
        console.log('Message Sent');
      }, function (err) {
        $scope.sendingError = true;
        console.error(err);
      })
      .finally(function () {
        $scope.sending = false;
      });
  }
})

.controller('AssociateCtrl', function ($scope, $state, API) {
  $scope.device = {};

  ionic.Platform.ready(function () {
    $scope.device.serialNumber = ionic.Platform.device().serial ? ionic.Platform.device().serial : getRandomSerialNumber();
  });

  $scope.associateDevice = function () {
    $scope.submitting = true;
    API.post('/devices', { serial: $scope.device.serialNumber })
      .then(function (response) {
        var device = response.data.device;
        delete $scope.device.serialNumber;
        $scope.device.associationCode = device.associationCode;

        API.put('/devices/' + device.id + '/associate', {device: $scope.device})
          .then(function (response) {
            localStorage.setItem('device', JSON.stringify(response.data.device));
            $state.go('tab.home');
          }, function (err) {
            alert(err);
          })
          .finally(function () {
            $scope.submitting = false;
          });
      }, function (err) {
        $scope.submitting = false;
        alert(err);
      });
  };

  function getRandomSerialNumber () {
    var serialNumber = '';
    var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

    for (var i = 0; i < 11; i++) {
      serialNumber += possible.charAt(Math.floor(Math.random() * possible.length));
    }

    return serialNumber;
  }
})

.controller('InfoCtrl', function ($scope, $state) {
  $scope.device = JSON.parse(localStorage.getItem('device'));

  if (!$scope.device) {
    $state.go('tab.associate');
  }
});

@@ -195,67 +195,47 @@
 %0A%0A  
-if (!
 $scope.
-device) %7B%0A    $state.go('tab.associate');%0A  %7D%0A%0A
+connect = function (device) %7B%0A  
   $s
@@ -260,16 +260,18 @@
 alse;%0A  
+ 
+ 
 $scope.c
@@ -289,16 +289,18 @@
  true;%0A%0A
+  
   MQTT.c
@@ -310,23 +310,16 @@
 ect(
-$scope.
 device)%0A
     
@@ -314,16 +314,18 @@
 device)%0A
+  
     .the
@@ -338,32 +338,34 @@
 tion () %7B%0A      
+  
 $scope.connected
@@ -375,24 +375,26 @@
 true;%0A      
+ 
+ 
 $scope.synci
@@ -400,24 +400,26 @@
 ing = true;%0A
+  
       MQTT.s
@@ -475,32 +475,34 @@
 tatus')%0A        
+  
 .then(function (
@@ -504,32 +504,34 @@
 ion (message) %7B%0A
+  
           $scope
@@ -556,32 +556,34 @@
 data;%0A          
+  
 localStorage.set
@@ -631,32 +631,34 @@
 a));%0A%0A          
+  
 $scope.synced = 
@@ -669,32 +669,34 @@
 Date();%0A        
+  
 %7D)%0A        .fina
@@ -682,32 +682,34 @@
      %7D)%0A        
+ 
+ 
 .finally(functio
@@ -707,32 +707,34 @@
 y(function () %7B%0A
+  
           $scope
@@ -755,28 +755,32 @@
 se;%0A        
+ 
+ 
 %7D);%0A
+  
     %7D, funct
@@ -790,24 +790,26 @@
  () %7B%0A      
+ 
+ 
 console.log(
@@ -836,27 +836,31 @@
 nect');%0A    
+  
 %7D)%0A
+  
     .finally
@@ -870,24 +870,26 @@
 nction () %7B%0A
+  
       $scope
@@ -917,73 +917,204 @@
     
+  
 %7D);%0A
-%7D)%0A%0A.controller('HomeCtrl', function ($scope, $state, MQTT) %7B
+  %7D;%0A%0A  if ($scope.device) %7B%0A    $scope.connect($scope.device);%0A  %7D%0A%7D)%0A%0A.controller('HomeCtrl', function ($scope, $state, MQTT) %7B%0A  if (!$scope.device) %7B%0A    $state.go('tab.associate');%0A  %7D%0A
 %0A  $
@@ -2559,32 +2559,79 @@
 on (response) %7B%0A
+            var device = response.data.device;%0A
             loca
@@ -2676,30 +2676,52 @@
 ify(
-response.data.
+device));%0A            $scope.connect(
 device)
-)
 ;%0A  

Move redirect to HomeCtrl + Add connect method on MainCtrl