'use strict';
/**
 * @ngdoc controller
 * @name SelectRemoteController
 * @description
 *  remote 목록을 표시하고 선택 후 remote 를 room 에 set 하는 화면
 */
app.controller('SelectRemoteController', function ($rootScope, $scope, $filter, $state, searchResults, toastr, Systems, Rooms) {
  $scope.searchKey = searchResults.searchKey;
  $scope.remotes = searchResults.searchedDevices;

  $scope.remoteType = 'CLIENTS';

  $scope.goBack = function () {
    $state.go('menu.programming.options');
  };

  $scope.doNext = function () {

    var currentSystem = Systems.getCurrentSystem(),
        remote = $scope.addRemote.selection,
        jsonData = JSON.stringify({ mac : remote.mac, name: remote.name + ' ' + remote.mac.slice(10,12) , type: remote.name, searchKey: $scope.searchKey });

    // remote 를 room 에 set(기존에 있으면 해당 것을 replace)
    var setRemote = function(roomId, json) {
      return Rooms.setRemote(roomId, json).then(function(data) { 
        toastr.success('Successfully added the remote with ID ' + $filter('remoteId')(remote.mac) +  ' to ' + $scope.addRemote.room.name + '.');
        return Systems.getCurrentSystem().id;
      });
    };

    var updateSystem = function(id) {
      return Systems.updateSystem(id).then(function (data) {
        console.log(data);
        return $state.transitionTo('menu.programming.options', {}, { reload: true, inherit: true, notify: true  });
      });
    };

    setRemote($scope.addRemote.room.id, jsonData)
      .then(updateSystem)
      .catch(function(error) {
        toastr.error(error, 'Error');
      });
  };

});


// app.controller('AvailableRoomsController', function ($scope, $filter, $state, toastr, Systems, Rooms) {

//   $scope.system = Systems.getCurrentSystem();

//   $scope.doNext = function () {

//     var remote = $scope.addRemote.selection,
//         jsonData = JSON.stringify({ mac : remote.mac, name: remote.name + ' ' + remote.mac.slice(10,12) , type: remote.name });

//     var setRemote = function(roomId, json) {
//       return Rooms.setRemote(roomId, json).then(function(data) { 
//         toastr.success('Successfully added the remote with ID ' + $filter('remoteId')(remote.mac) +  ' to ' + $scope.addRemote.room.name + '.');
//         return Systems.getCurrentSystem().id;
//       });
//     };

//     var updateSystem = function(id) {
//       return Systems.updateSystem(id).then(function (data) {
//         console.log(data);
//         return $state.transitionTo('menu.advanced.options', {}, { reload: true, inherit: true, notify: true  });
//       });
//     }

//     setRemote($scope.addRemote.room.id, jsonData)
//       .then(updateSystem)
//       .catch(function(error) {
//         toastr.error(error, 'Error');
//       });
//   };

// });
