'use strict';

app.controller('PunchToDeviceController', function ($scope, $state, deviceId) {
  $scope.doNext = function() {
    $state.go('menu.programming.volume-control.punch-from-device');
  };
});



app.controller('PunchFromDeviceController', function ($scope, $state, $http, Systems) {
  

  var punchVolId = $scope.volumeControl.punchTo.punch_vol;

  if (!_.isEmpty($scope.volumeControl.punchTo) && punchVolId !== -1 ) {
    //check to see if it's not empty to avoid error on state reload
    var punchFromDevice = _.find($scope.volumeControl.devices.source, { 'id': $scope.volumeControl.punchTo.punch_vol });
    console.log(punchFromDevice);
    $scope.volumeControl.punchFrom = punchFromDevice ;
  }


  $scope.finish = function() {
    var punchTo = $scope.volumeControl.punchTo;
    var punchFrom = $scope.volumeControl.punchFrom;

    if (punchTo.punch_vol === punchFrom.id ) {
      //if data is same, skip send to server 
      console.log('skipping send to server');
      $state.go('menu.programming.options');

    } else {
      //else send to server and update client
      var jsonData = JSON.stringify( { punchFrom : punchFrom.id });
    
      $http({
        method: 'POST',
        url: '/urcassistant/api/device/punch/' + $scope.room.id + '/' + punchTo.id,
        data : jsonData
      }).
      success(function(data) {
        if(data.result) {

          if (punchTo.id) { 
            //if the punchTo device is not the Main device, update the client
            var currentSystem = Systems.getCurrentSystem();        
            var roomIndex = _.findIndex(currentSystem.rooms, { 'id': $scope.room.id });      
            var deviceIndex = _.findIndex(currentSystem.rooms[roomIndex].devices, { 'id': punchTo.id });
            var currentDevice = currentSystem.rooms[roomIndex].devices[deviceIndex];        
            currentDevice.punch_vol =  punchTo.id !== punchFrom.id ? punchFrom.id : -1;

            Systems.loadSystem(currentSystem);
          }

          
          $state.transitionTo('menu.programming.options', null, { reload: true, inherit: true, notify: true  });

        }
        else {
          alert(data.error);
        }
      }).
      error(function() {
        alert("Please try again");
      });
    } 
  };
  
});