var angular = require('angular');
var _ = require('jsUtil');
require('../modules');
require('../../appInitFlow/services/appInitFlow');
  'use strict';

  var module = angular.module('notice.services');

  module.run(function($rootScope, WebSocketService, CoreAppConfig, appInitFlowService) {
    /** 验证服务器的连通状态，如果连通建立websocket,未连通关闭websocket */
    $rootScope.$watch('connected', function(connected) {
      var webSocketServerUrl = CoreAppConfig.applicationConfig.getWebSocketServerUrl();
      if (!webSocketServerUrl) {
        return;
      }
      if (connected) {
        WebSocketService.buildWebsocket(window.device.uuid).then(function() {
          WebSocketService.bindCurrentUser();
        });
      } else {
        WebSocketService.closeWebsocket();
      }
    });

    $rootScope.$on('login.buildWebsocket', function() { // 身份验证成功
      WebSocketService.bindCurrentUser();
    });

    $rootScope.$on('serverUrl.changed', function() {
      if ($rootScope.connected) {
        WebSocketService.buildWebsocket(window.device.uuid).then(function() {
          WebSocketService.bindCurrentUser();
        });
      }
    });

    $rootScope.$on('actionSuccess', function($event, actionName) {
      if (actionName === appInitFlowService.SET_URL) {
        if ($rootScope.connected) {
          WebSocketService.buildWebsocket(window.device.uuid).then(function() {
            WebSocketService.bindCurrentUser();
          });
        }
      }
	});
  });

  module.factory('WebSocketConfig', function() {
    var handlerMap = {};

    function registerHandler(type, fn) {
      handlerMap[type] = fn;
    }

    function getHandler(type) {
      return handlerMap[type];
    }

    return {
      registerHandler: registerHandler,

      getHandler: getHandler
    };
  });

  module.factory('WebSocketService', function($rootScope, CoreAppConfig,
    ContinuousWebSocket, WebSocketConfig, LinkerService, $q) {
    var websocket;
    var webSocketServerUrl = CoreAppConfig.applicationConfig.getWebSocketServerUrl();

    /**
     * 获取WebSocket连接
     *
     * @param  {String} deviceId 设备ID
     * @return {String} 返回WebSocket连接
     */
    function getWsUrl(deviceId) {
      return webSocketServerUrl + '/' + deviceId;
    }

    function getWebsocket() {
      return websocket;
    }

    /**
     * 服务器端向客户端推送消息。
     * type: 'message'，服务器端向发送人发送消息
     * type: 'message.receipt'，服务器端向发送人发送回执消息
     * type: 'message.read.receipt'，客户端发送已读消息回执
     * type: 'jfw'，服务器端向客户端推送的局发文未读数目和最新通知
     * type: 'DispatchNotice'，服务器向客户端推送的任务分发消息
     * @param  {[type]} event [description]
     * @return {[type]}       [description]
     */
    function onMessage(event) {
      var data = JSON.parse(event.data);
      var handler = WebSocketConfig.getHandler(data.type);
      if (handler) {
        handler(data.data);
      } else {
        $rootScope.$broadcast('websocket.notice', data);
      }
    }

    /**
    * 发送当前登录用户到服务器,让当前的登录用户与设备绑定
    *
    * @param {String} deviceId 设备ID
    * @param {String} userId 用户ID
    */
    function bindUser(deviceId, userId) {
      if (websocket && websocket.webSocket) {
        websocket.url = getWsUrl(deviceId) + '?userId=' + userId;
        websocket.webSocket.send(JSON.stringify({
          type: 'user',
          data: {
            deviceId: deviceId,
            userId: userId
          }
        }));
      }
    }

    /**
    * 设备与当前用户绑定
    */
    function bindCurrentUser() {
      var userId = LinkerService.currentUserId;
      if (userId) {
         bindUser(window.device.uuid, userId);
      }
    }

    /**
    * 建立webSocket连接
    *
    * @param {String} deviceId 设备ID
    */
    function buildWebsocket(deviceId) {
      var deferred = $q.defer();

      if (websocket && websocket.wsUrl === getWsUrl(deviceId)) {
        websocket.open();
      } else if (websocket && websocket.wsUrl !== getWsUrl(deviceId)) {
        websocket.changeUrl(getWsUrl(deviceId));
      } else {
        websocket = new ContinuousWebSocket(getWsUrl(deviceId));

        websocket.onmessage = function(event) {
          onMessage(event);
        };

        websocket.onopen = function() {
          console.log('socket连接已建立。');
          deferred.resolve(true);
        };

        websocket.onerror = function() {
          console.log('socket连接有问题。');
          deferred.reject(false);
        };
      }
      websocket.wsUrl = getWsUrl(deviceId);
      return deferred.promise;
    }

    function closeWebsocket() {
      if (websocket) {
        websocket.close();
      }
    }

    return {
      buildWebsocket: buildWebsocket,
      getWebsocket: getWebsocket,
      bindUser: bindUser,
      closeWebsocket: closeWebsocket,
      bindCurrentUser: bindCurrentUser
    };

  });
