package com.pingpang.websocketchat.send.impl;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.pingpang.redis.RedisPre;
import com.pingpang.util.StringUtil;
import com.pingpang.websocketchat.ChannelManager;
import com.pingpang.websocketchat.ChatType;
import com.pingpang.websocketchat.ChatUserBind;
import com.pingpang.websocketchat.Message;
import com.pingpang.websocketchat.send.ChatSend;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * 绑定操作
 * @author dell
 */
public class ChatSendBind extends ChatSend{

	@Override
	public void send(Message message, ChannelHandlerContext ctx) throws JsonProcessingException {
		
	   InetSocketAddress ipSocket = (InetSocketAddress)ctx.channel().remoteAddress();
	   String clientIp = ipSocket.getAddress().getHostAddress();
	   
	   logger.info("用户{},绑定IP{}",message.getFrom().getUserCode(),clientIp);
	   
	   ChatUserBind cub=new ChatUserBind(message.getFrom().getUserCode(),clientIp,"2");
	   userMsgService.addUserBind(cub);
	   
	   message.setFrom(userService.getUser(message.getFrom()));
       
	   String loginToken=(String) redisService.get(RedisPre.DB_USER_LOGIN_TOKEN+message.getFrom().getUserCode());
	   if(StringUtil.isNUll(loginToken) || !loginToken.equals(message.getMsg())) {
		   message.setCmd(ChatType.LEAVE);
		   message.setMsg("连接服务端验证失败");
		   ctx.channel().writeAndFlush(new TextWebSocketFrame(this.getMapper().writeValueAsString(message)));
           return;
	   }else {
		   redisService.delete(RedisPre.DB_USER_LOGIN_TOKEN+message.getFrom().getUserCode());
	   }
	   
	   //这里主要更新了IP发送消息做数据记录 
	   //redisService.set(RedisPre.DB_USER+message.getFrom().getUserCode(), message.getFrom());
	   redisService.addHashMap(RedisPre.DB_USER+message.getFrom().getUserCode(), "ip", clientIp);
	   //用户状态-1:注销,0:离线,1:在线,2:禁言
	   if("0".equals(message.getFrom().getUserStatus())) {
		   redisService.addHashMap(RedisPre.DB_USER+message.getFrom().getUserCode(), "userStatus", "1");
	   }else if("-1".equals(message.getFrom().getUserStatus())) {
		   ctx.writeAndFlush(new TextWebSocketFrame(this.getMapper().writeValueAsString(this.getAdmessag("系统消息此用户已被注销","-1"))));
           return;
	   }
	   
	   redisService.addSet(RedisPre.NETTY_USER_SET, message.getFrom());
	   
	   ChannelManager.addChannel(message.getFrom(), ctx.channel());
	   
	   Message bindSucMsg=new Message();
	   bindSucMsg.setCmd("1");
	   ctx.channel().writeAndFlush(new TextWebSocketFrame(this.getMapper().writeValueAsString(bindSucMsg)));		
		
	   /**
		 * 获取离线消息，并推送
		 */
		List<Message> outMsg=userMsgService.getUserOutMsg(message.getFrom());
		if(null!=outMsg && !outMsg.isEmpty()) {
			
			Set<String> messageIDs=new HashSet<String>();
			Map<String,Object> updateMap=new HashMap<String, Object>();
			updateMap.put("status", "1");
			updateMap.put("IP", clientIp);
				for(Message m : outMsg) {
					messageIDs.add(m.getId());
					m.setCmd("2");//当作离线通知和下线提醒
					ctx.channel().writeAndFlush(new TextWebSocketFrame(this.getMapper().writeValueAsString(m)));		
			  }
				/**
				 * 更新数据状态
				 */
				updateMap.put("ids", messageIDs);
				userMsgService.upOutMsg(updateMap); 				
		}
	}

}
