'use strict';


app.controller('SystemSelectController', function ($scope, $state, $modal, toastr, resolvedSystems, Devices, Systems) {

  	$scope.systems = resolvedSystems;

    $scope.doNext = function(){
      Systems.setCurrentRoom(null);

      var selectedSystem = _.findWhere($scope.systems, {
        id: $scope.choice
      });

      // dealer 에게 assign 된 system 인 경우
      if (selectedSystem.dealer_id) {
        // user-login-change 로 이동시킴
        window.location = '/user-login-change#/auto-login/' + $scope.choice + '/' + selectedSystem.dealer_id;
      }
      // 일반 system
      else {
        return Systems.updateSystem($scope.choice).then(
          function (data) {
            var masterBstation;
            _.each(data.rooms, function(room) {
              if (!masterBstation) {
                masterBstation = _.where(room.bstations, {
                  master: 1
                })[0];
              }
            });
            if (!masterBstation) {
              $state.go('recovery-bstation', {rooms: angular.toJson(data.rooms)});
              return;
            }

            // TRF-ZW data update
            _.each(data.rooms, function(room) {
              var trfzw = _.find(room.twoway_devices, {model: 'TRF-ZW1'});
              if (trfzw) {
                Devices.updateTwowayDevice(room.id, trfzw.id)
                  .then(function(data) {
                    trfzw.data = data;
                  }, function() {
                    var modal = $modal({
                      container: '.editor-container',
                      template: 'views/modal-tpls/connection-problem.html',
                      show: false
                    });

                    modal.$promise.then(modal.show);
                  })
                  .catch(toastr.error);

                return false;
              }
            });

            $state.go('menu.system-overview');
          },
          function (error) {
            toastr.error(error);
          }
        );
      }
    };

});

/**
 * @ngdoc controller
 * @name SystemDeleteController
 * @description
 *  system 목록 표시, system 삭제 화면
 */
app.controller('SystemDeleteController', function ($rootScope, $scope, $state, toastr, resolvedSystems, Systems, User) {

    var currentSystemId = Systems.getCurrentSystem().id;
  $scope.currentSystemId = currentSystemId;

    $scope.systems = resolvedSystems;
    $scope.sysToDel = {};

    $scope.deleteSystem = function(){

      // system 삭제
      Systems.deleteSystem($scope.sysToDel.id).then(function (data) {
          // dealer 로그인 상태이면서 삭제하려는 system 이 현재 system 인 경우
          if ($rootScope.dealerCompany && currentSystemId === $scope.sysToDel.id) {
            $state.go('dealer-jobs-list');
          } else {
            // 남은 system 이 없는 경우 system 등록 화면으로 이동
            if (Systems.getAll().length === 0) {
              User.logout().then(function () {
                $state.transitionTo('register', null, {reload: true, inherit: true, notify: true});
              });
            }
            // 삭제한 system 이 현재 system 이었던 경우 system 선택 화면으로 이동
            else if (currentSystemId === $scope.sysToDel.id) {
              $state.go('system-select');
            }
            // 삭제한 system 이 현재 system 이 아니었던 경우 현재 system 의 home overview 화면으로 이동
            else {
              $state.go('menu.system-overview');
            }
          }
        },
        function (error) {
          toastr.error(error);
        }
      );
    };

});

/**
 * @ngdoc controller
 * @name SystemSettingsController
 * @description
 *  system 설정 메인 화면
 */
app.controller('SystemSettingsController', function ($scope, $modal, $http, $window, timeZones, currentSystem, Auth) {

  $scope.system = currentSystem;
  $scope.timeZones = timeZones;

  $scope.factoryUser = false;

  $scope.currentUser = JSON.parse($window.localStorage.getItem('hcm_editor'));

  // 현재 로그인한 사용자가 factory_user.json 에 있는지 검사
  $http.get('/scripts/factory_user.json')
    .success(function(response) {
      if (response && response.users) {
        Auth.currentUser().then(function(user) {
          if (response.users.indexOf(user.username) > -1) {
            $scope.factoryUser = true;
          }
        });
      }
    });

});

/**
 * @ngdoc controller
 * @name ChangeMasterFromFactoryController
 * @description
 *  factory master change 화면
 */
app.controller('ChangeMasterFromFactoryController', function ($rootScope, $scope, $state, toastr, searchResults, Systems) {
  $scope.baseStations = searchResults.searchedDevices;
  $scope.bsReplace = {};

  var systemId = Systems.getCurrentSystem().id;

  var orgMac = Systems.getCurrentSystem().rooms[0].bstations[0].mac;

  $scope.doNext = function() {
    var jsonData = JSON.stringify({ modelType: $scope.bsReplace.target.name, mac: $scope.bsReplace.target.mac, org_mac: orgMac });
    Systems.changeMasterFromFactory(systemId, jsonData)
      .then(function(data) {
        Systems.updateSystem(systemId).then(function () {
          $state.go('system-settings.change-master-from-factory-success');
        });
      })
      .catch(toastr.error);
  };
});

app.controller('ChangeMasterFromFactorySuccessController', function ($rootScope, $scope, $state) {
  $scope.doNext = function() {
    $state.go('system-settings.main');
  };
});

/**
 * @ngdoc controller
 * @name ReplaceMainController
 * @description
 *  변경할 base station 선택 화면
 */
app.controller('ReplaceMainController', function  ($scope, $state){

  $scope.doNext = function () {
    if ($scope.bsReplace.selection.master) {
      $state.go('system-settings.replace.master');
    } else {
      $state.go('system-settings.replace.slave');
    }
  };
});

app.controller('ReplaceMasterController', function  ($rootScope, $scope, $state, Systems, availableModels){
  $scope.bsReplace.modelType = availableModels[0];
  $scope.availableModels = availableModels;


  $scope.doNext = function () {
    var key = $scope.bsReplace.key.first + $scope.bsReplace.key.second + $scope.bsReplace.key.third + $scope.bsReplace.key.fourth,
        key = key.toUpperCase(),
        type = $scope.bsReplace.modelType,
        jsonData = JSON.stringify({ modelType: type, key: key});

    console.log(jsonData);
    Systems.checkKey(jsonData).then(function(data) {
      console.log(data);
      $scope.bsReplace.target = data;
      $state.go('system-settings.replace.target');
    })
    .catch(function(error) {
      alert(error);
    });
  };
  
});

app.controller('ReplaceSlaveController', function  ($rootScope, $scope, $state, searchResults){
  $scope.baseStations = searchResults.searchedDevices;

  $scope.bsType = 'BASESTATIONS';

  $scope.doNext = function () {
    //$scope.bsReplace.target = angular.copy($scope.bsReplace.bsSelect);
    $state.go('system-settings.replace.target');
  };
});

app.controller('ReplaceTargetController', function  ($scope, $state, toastr, Systems, Rooms){
  // base station 이름 변경: modelType + macAddress 맨 끝 2자리 ex) HS-C100 EE
  function editBstation() {
    var roomId,
      bstation = {},
      orgMac = $scope.bsReplace.selection.mac,
      mac,
      type;

    _.each($scope.system.rooms, function(room) {
      _.each(room.bstations, function(bstation) {
        if (bstation.mac == orgMac) {
          roomId = room.id;
        }
      });
    });

    if ($scope.bsReplace.selection.master) {
      mac = $scope.bsReplace.key.first + $scope.bsReplace.key.second + $scope.bsReplace.key.third + $scope.bsReplace.key.fourth;
      mac = mac.toUpperCase();
      mac = mac.substr(4);
      type = $scope.bsReplace.modelType;
    } else {
      mac = $scope.bsReplace.target.mac;
      type = $scope.bsReplace.target.name;
    }

    bstation.mac = mac;
    bstation.type = type;
    bstation.name = type + ' ' + mac.substr(10);
    bstation.light_level = 2;

    var jsonData = JSON.stringify( { name : bstation.name, mac: bstation.mac, type: bstation.type, lightLevel: bstation.light_level } );
    // base station 의 type, name, lightLevel 을 설정

    Rooms.baseStations('edit', roomId, jsonData).
      then(function(data) {

      }).
      catch(toastr.error);
  }

  var changeMaster = function(json) {
    return Systems.changeMaster(json).then(function(data) { 
      return Systems.getCurrentSystem().id;
    });
  };

  var changeSlave = function(json) {
    return Systems.changeSlave(json).then(function(data) { 
      return Systems.getCurrentSystem().id;
    });
  };

  var updateSystem = function(id) {
    editBstation();

    return Systems.updateSystem(id).then(function (data) {
      console.log(data);
      return $state.transitionTo('system-settings.replace.prompt', {}, { reload: true, inherit: true, notify: true  });
    });
  };


  $scope.replace = function () {

    if ($scope.bsReplace.selection.master) {
      var key = $scope.bsReplace.key.first + $scope.bsReplace.key.second + $scope.bsReplace.key.third + $scope.bsReplace.key.fourth,
          key = key.toUpperCase(),
          type = $scope.bsReplace.modelType;


      changeMaster(JSON.stringify({ org_mac: $scope.bsReplace.selection.mac, modelType: type, key: key}))
        .then(updateSystem)
        .catch(function (error) {
          alert(error);
        });
      

    } else {

      changeSlave(JSON.stringify({ org_mac: $scope.bsReplace.selection.mac, new_mac: $scope.bsReplace.target.mac, modelType: $scope.bsReplace.target.name }))
        .then(updateSystem)
        .catch(function (error) {
          alert(error);
        });
    }
    
  };
});

app.controller('ReplacePromptController', function  ($scope, $state){
  
});

/**
 * @ngdoc controller
 * @name SystemOverviewController
 * @description
 *  system overview 화면
 */
app.controller('SystemOverviewController', function ($rootScope, $scope, $http, $modal, $popover, $state, toastr, types, Systems, Rooms, Database, Devices) {
  $scope.types = types;

  // scheduled event 기능을 eng, alpha 버전에서만 보이게 하기 위한 처리
  if ($rootScope.version.substr(-1) === 'e' || $rootScope.version.substr(-1) === 'a') {
    $scope.isAlpha = true;
  } else {
    $scope.isAlpha = false;
  }

  $scope.system = Systems.getCurrentSystem();
  $scope.selections = { 'selectedRoom': {}, 'selectedBstation': {}, 'selectedRemote': {}, 'selectedDevice': {}};

  var favoriteOptionModal = $modal({
    scope: $scope,
    title: 'Add Favorite Channels to this device',
    placement: 'top',
    template: 'views/modal-tpls/system-overview/fav-option.html',
    container: '#system-overview',
    show: false
  });

  $scope.popover = { 'device': '', 'twowayDevice': ''};

  $scope.findPunchDevice = function(room) {
    $scope.popover.punchName = _.find(room.devices, { 'id': $scope.popover.device.punch_vol }).name;
  };

  $scope.findPunchTwowayDevice = function(room) {
    var trfzw = _.find($scope.system.rooms[0].twoway_devices, {model: 'TRF-ZW1'}),
      item = _.find(trfzw.extra_info.punch, {roomId: room.id});

    $scope.popover.punchName = _.find(room.devices, { 'id': item.from }) ? _.find(room.devices, { 'id': item.from }).name : '';
  };

  $scope.containsMaster = function(room) {
    return _.contains(_.pluck(room.bstations, 'master'), 1);
  };

  $scope.changeValue = function(value) {
    return value/1000;
  };

  $scope.isEntDevice = Database.checkIfEntertainment;

  $scope.showFavModal = function (room, device) {
    angular.copy(room, $scope.selections.selectedRoom);
    angular.copy(device, $scope.selections.selectedDevice);

    favoriteOptionModal.$promise.then(favoriteOptionModal.show);
  };


  $scope.toggleFavorite = function(room, device) {
    var currentSystem = Systems.getCurrentSystem(),
            roomIndex = _.findIndex(currentSystem.rooms, { 'id': room.id }),
          deviceIndex = _.findIndex(currentSystem.rooms[roomIndex].devices, { 'id': device.id }),
        currentDevice = currentSystem.rooms[roomIndex].devices[deviceIndex];

    if (!_.isEqual(currentDevice, device)) {
      var jsonData =  { "favOption": device.fav_option, "favDelay": device.fav_delay, "favEnter": device.fav_enter  };
      console.log(jsonData);

      var url;
      if ($rootScope.virtualEditor) {
        url = '/api/dealer/device/favorite/' + room.id + '/' + device.id;
      } else {
        url = '/api/device/favorite/' + room.id + '/' + device.id;
      }

      // favorite option 변경 API 호출
      $http({
        method: 'POST',
        url: url,
        data : jsonData
      }).
      success(function(data) {
        if(data.result) {
          currentDevice.fav_option = device.fav_option;
          currentDevice.fav_delay = device.fav_delay;
          currentDevice.fav_enter = device.fav_enter;
          Systems.loadSystem(currentSystem);
          $state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
        }
        else {
          toastr.error(data.error);
        }
      })
      .error(function(error) {
        toastr.error('Please try again');
      });
    }

  };

  $scope.changeEventState = function(systemId, roomId, eventId, defaultState) {
    if (defaultState) {
      defaultState = 1;
    } else {
      defaultState = 0;
    }

    var jsonData = JSON.stringify({ id: eventId, default_state: defaultState });
    Rooms.changeEventState(systemId, roomId, jsonData)
      .then(function(data) {
        Systems.updateSystem(systemId).then(function () {
        });
      })
      .catch(toastr.error);
  };

  Rooms.disableScheEventEdit();
  Rooms.setScheEventData(null);

  $scope.eventEdit = function(room, event) {
    Rooms.enableScheEventEdit();

    Rooms.setScheEventData({
      room: angular.copy(room),
      event: angular.copy(event)
    });

    $state.go('menu.advanced.add-macros.sche-event-edit');
  };
  
});
