# chat/chatManager.js

    ModuleBase.define("ChatManager", ["Message","Error"], function(Message, Error) {

    	var ChatManager = function() {

    	    /**
             * ChatManager级别回调的枚举
             * @readonly
             * @enum {string}
             */
    		 this.ChatManagerCallbackEnum = {
    			  RECEIVE_MESSAGE_NOTIFY: 'receive.message.notify',
    			  MESSAGE_STATUS_CHANGED_NOTIFY: 'message.status.changed.notify'
    		 };

    		 /**
             * @desc Session Type
             * @enum {number}
             */
    		 this.SessionTypeEnum =  {
    	          peers: 1,    //单聊
    	          group: 2,    //群组
    	          chatroom: 3  //聊天室
            };

             /**
             * @desc 消息类型
             * @enum {number}
             */
             this.MessageTypeEnum =  {
    	          text: 0x01,		 //文本
    	          image: 0x02,	     //图片
    	          file: 0x03,		 //文件
    	          audio: 0x04,	     //声音
    	          video: 0x05,	     //视频
    	          location: 0x06,	 //位置
    	     };

    		 /**
    		 * @desc 消息状态
    		 * @enum {number}
    		 */
    		 this.MessageStatussEnum =  {
    			 delivering: 1,	  //传送中(发送端)
    			 delivered: 2,    //传送成功或接收成功 (发送端及接收端)
    			 read: 3,         //已读 (接收端）
    			 failed: 4,	      //传送失败(发送端)
    			 recalled: 5      //召回（发送端及接收端）
    	    };

    		this.eventEmitter = new EventEmitter();
    	};

        ChatManager.prototype.registerGroups = function(groupIds){
        	     if(groupIds){
        	     	  for(var i = 0; i < groupIds.length; i++) {
    			      var groupId = groupIds[i];
    			      signalClient.rtmServer.subscribe("/g/"+groupId);
    			   }
    		 }
        }

        ChatManager.prototype.unregisterGroup = function(groupId){
        	     if(groupId){
        	     	signalClient.rtmServer.unsubscribe("/g/"+groupId);
        	     }
        }

        ChatManager.prototype.newTextMessage = function(sessionType,sessionId,content){
             var self = this;
             var uuid =  Math.uuid();
    		 var newMessage = new Message(uuid,sessionType, sessionId);
    		 newMessage.sendUserId = signalClient.selfUser.userId;
    		 newMessage.messageType = self.MessageTypeEnum.text;
    		 newMessage.content = content;
    		 newMessage.createTime = signalClient.getServeTime();
    		 newMessage.status = self.MessageStatussEnum.delivering;
    		 return newMessage;
        };

    	ChatManager.prototype.sendMessage = function(message){
    		 var self = this;
    		 var deferred = when.defer();
    		 var topic = "/u/" +  message.sessionId;
    		 if(message.sessionType  != self.SessionTypeEnum.peers){
    		 	 topic = "/g/" +  message.sessionId;
    		 }
    		 signalClient.rtmServer.sendMsgData(topic,message).then(function() {
    		 	   deferred.resolve();
    		 }).otherwise(function(error) {
    		 	   deferred.reject(error);
    		 });

    		 return deferred.promise;
    	}

    	/**
    	 * @desc emitReceiveMessageNotify
    	 * @ignore
    	 */
    	ChatManager.prototype.emitReceiveMessageNotify = function(fromUserId,msg_id,session_type,session_id,create_time,msg_type,msg_content){
    		 var message = new Message(msg_id,session_type,session_id);
    		 message.sendUserId = fromUserId;
    		 message.messageType = msg_type;
    		 var msgContent = new Uint8Array(msg_content);
    		 message.content = typeConversionUtil.Uint8ArrayToString(msgContent);
    		 message.createTime = create_time;
    		 message.status = this.MessageStatussEnum.delivered;

    		 this.eventEmitter.emit(this.ChatManagerCallbackEnum.RECEIVE_MESSAGE_NOTIFY,message);
    	}

    	ChatManager.prototype.sendImageMessage = function(sessionId,sessionType,imageContent,imagePath){

    	}

    	ChatManager.prototype.sendFileMessage = function(sessionId,sessionType,fileContent,filePath){

    	}

    	ChatManager.prototype.sendAudioMessage = function(sessionId,sessionType,audioContent,audioPath){

    	}

    	//已读消息
    	ChatManager.prototype.readMessage = function(messageId){

    	}

    	//撤回消息
    	ChatManager.prototype.recallMessage = function(messageId){

    	}

    	/**
         * @desc ChatManager级别的回调
         * @param {ChatManagerCallback} type - 回调枚举标识
         * @param {Object} callback -回调方法名,可以自定义
         * @example
         *  chatManager.addCallback(chatManager.ChatManagerCallbackEnum.RECEIVE_MESSAGE_NOTIFY, onReceiveMessageNotify);
         *  chatManager.addCallback(chatManager.ChatManagerCallbackEnum.MESSAGE_STATUS_CHANGED_NOTIFY, onMessageStatusChangedNotify);
         *
         * function onReceiveMessageNotify(message){
         *
         * }
         *
         * function onMessageStatusChangedNotify(messageStatus,sessionId,sesstionType,messageId){
         *
         * }
         *
         */
    	ChatManager.prototype.addCallback = function(type, callback) {
    		  this.eventEmitter.on(type, callback);
    	};

    	ChatManager.prototype.offCallback = function(types) {
    		   for(var key in types) {
    	           var type = types[key];
    		   	   this.eventEmitter.off(type);
    		   }
    	};

        return ChatManager;

    });