'use strict';

var angular = require('angular');
require('uiRouter');
require('./modules');
require('./services/DeviceManager');
require('../notice/services/WebSocketService');
require('../gesturepassword/services/GesturePasswordService');

var module = angular.module('devicemanager');

module.run(function(AppConfig, $rootScope, DeviceManager, WebSocketConfig,
  $state, LinkerService, $stateParams, GesturePasswordService) {
  $rootScope.$on('login', function($event, data) {
    DeviceManager.applyDeviceStateData(data.deviceInfo);
  });

  AppConfig.addSetItem({
    text: '设备管理',
    state: 'devicemanager.accountProtect',
    order: 3
  });
  //设备绑定监听
  WebSocketConfig.registerHandler('DEVICE_BIND', function(deviceInfo) {
    //TODO 通过websocket推送黑白名单的信息时，需要将这段代码删除
    var _deviceInfo = JSON.parse(localStorage.getItem('deviceStatus')) || {};
    deviceInfo.inWhiteList = _deviceInfo.inWhiteList;
    DeviceManager.changeDeviceInfo(deviceInfo);
  });

  //设备锁定监听
  WebSocketConfig.registerHandler('DEVICE_INFO', function(device) {
    DeviceManager.setLockStatus(device.lockStatus);
  });

  // WebSocketConfig.registerHandler('DEVICE_LOCK_ACTION', function(lockStatus) {});
  // WebSocketConfig.registerHandler('DEVICE_BIND_ACTION', function(lockStatus) {});

  $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
    if ('devicemanager.lockPage' !== toState.name && DeviceManager.isLocked()) {
      event.preventDefault();
      $state.go('devicemanager.lockPage');
    }
  });

  $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
    if ('devicemanager.lockPage' === toState.name ||
      'devicemanager.unBinded' === toState.name ||
      'devicemanager.bindedToOtherUser' === toState.name ||
      'login' === toState.name ||
      'calogin' === toState.name) {
      GesturePasswordService.completed = false;
    }
  });

});
