'use strict';

var angular = require('angular');
require('../../notice/services/WebSocketService');
require('../../appInitFlow/services/appInitFlow');

var module = angular.module('onlinemonitor.services', ['notice.services', 'appInitFlow.services']);

module.run(function($rootScope, $timeout, WebSocketConfig, userStatusMonitor, appInitFlowService) {
  //注册监听事件
  WebSocketConfig.registerHandler('MONITOR_OTHER', userStatusMonitor.otherLogin);

  $rootScope.$on('actionSuccess', function($event, actionName) {
    if (actionName === appInitFlowService.AUTHENTICATE) {
      $timeout(function() {
        userStatusMonitor.regularTasks();
      });
    }
  });
});
module.factory('userStatusMonitor', function($rootScope, $http, LinkerService, 
  Timer, $toast, WebSocketService) {
  var intervalTimerId;
  /**
   * 保存&更新在线状态
   * @param  {[type]} callbackFn [description]
   * @return {[type]}            [description]
   */
  function saveMonitorInfo(callbackFn) {
    if (!$rootScope.connected) {
      return;
    }
    
    var monitor = {
      'userId': LinkerService.currentUserId,
      'devSn': window.device.uuid,
      'status': '1',
      'timeOfLastLogin': new Date(),//当前时间
      'devName':window.device.model
    };

    updateMonitor(monitor);
    callbackFn && callbackFn();
  }
  /**
   * 更新数据
   */
  function updateMonitor(monitor) {
    var message = {
      'type': 'onlinemonitor',
      'data': monitor
    };
    WebSocketService.getWebsocket().send(JSON.stringify(message));
  }
  /**
   * 定时更新在线状态
   * 1分钟
   */
  function regularTasks() {
    if (!intervalTimerId) {
      intervalTimerId = Timer.interval(saveMonitorInfo, 60000);
    }
    saveMonitorInfo();
  }

  /**
   * 监听退出事件，告知服务器，已离线
   */
  $rootScope.$on('logout', function(event, userId) {
    var monitor = {
      'userId': userId,
      'devSn': window.device.uuid,
      'status': '0',
      'timeOfLastLogin': new Date(),//当前时间
      'devName':window.device.model
    };
    clearInterval(intervalTimerId);
    updateMonitor(monitor);
  });

  $rootScope.$on('login', function() {
    localStorage.monitorUserId = LinkerService.currentUserId;
  });

  var monitor = {
    regularTasks : regularTasks,
    otherLogin: function(monitor) {
      $toast.showLongTop('您的账号于' + monitor.timeOfLastLogin.replace(/T|\..*/g, ' ').trim() + '在'
       + monitor.devName + '('+ monitor.devSn + ')设备上登录！');
    }
  };
  return monitor;
});
