'use strict';
/**
 * @ngdoc controller
 * @name SelectBaseController
 * @description
 *  base station 목록 표시 및 추가
 */
app.controller('SelectBaseController', function ($rootScope, $scope, $state, toastr, searchResults, Systems, Rooms ) {
  $scope.searchKey = searchResults.searchKey;
  $scope.baseStations = searchResults.searchedDevices;

  $scope.bsType = 'BASESTATIONS';

  $scope.changedValue = function() {
    if (!$scope.addBStationForm.displayText.$dirty) {
      var bs = $scope.addBaseStation.selection;
      $scope.addBaseStation.displayText =  bs.name + ' ' + bs.mac.slice(10,12);
    }
  };

  $scope.finish = function () {
    var currentSystem = Systems.getCurrentSystem(),
            givenName = $scope.addBaseStation.displayText,
          baseStation = $scope.addBaseStation.selection,
             jsonData = JSON.stringify({ mac : baseStation.mac, type : baseStation.name, name: givenName, lightLevel: 2, searchKey: $scope.searchKey });

    // slave base station 을 room 에 추가
    var addBStation = function(roomId, json) {
      return Rooms.baseStations('add', roomId, json).then(function(data) { 
        toastr.success('Successfully added ' + givenName + '.');
        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  });
        //$state.go('menu.programming.option');
      });
    };

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

  };
});