package com.pingpang.websocketchat.send.impl;

import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.pingpang.util.StringUtil;
import com.pingpang.websocketchat.ChannelManager;
import com.pingpang.websocketchat.ChartUser;
import com.pingpang.websocketchat.ChatType;
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 ChatSendSingle extends ChatSend{

	@Override
	public void send(Message message, ChannelHandlerContext ctx) throws JsonProcessingException {
		
		/*
		 * if(!ChannelManager.isExitChannel(message.getAccept())) {
		 * this.redisService.SendMsg(message); return; }
		 */
		
		if (null != ChannelManager.getChannel(message.getAccept().getUserCode())) {
			
			//发送数据这里改为redis
			message.getFrom().setUserPassword("");
			message.getAccept().setUserPassword("");
			
			ChartUser fromUser =userService.getUser(message.getFrom());
			
			//判断广播消息 因为管理员没绑定信息
			if(!(null==fromUser && "admin".equals(message.getFrom().getUserCode()))) {
			   message.setFrom(fromUser);
			}
			
			message.setAccept(userService.getUser(message.getAccept()));
			
			ChannelManager.getChannel(message.getAccept().getUserCode())
					.writeAndFlush(new TextWebSocketFrame(this.getMapper().writeValueAsString(message)));
			
			//已经保存的临时数据
			if(StringUtil.isNUll(message.getId())) {
				message.setStatus("1");
				userMsgService.addMsg(message);
			}else {//更新数据状态
				Map<String,Object> upMsg=new HashMap<String, Object>();
	       	    upMsg.put("id",message.getId().split(",",-1));
	            upMsg.put("status","1");
	            this.userMsgService.upMsg(upMsg); 	
			}
		} else {
			message.setStatus("0");
			//message.setFrom(ChannelManager.getChartUser(message.getFrom().getUserCode()));
			message.setFrom(userService.getUser(message.getFrom()));
			message.setAccept(this.userService.getUser(message.getAccept()));
			userMsgService.addMsg(message);
			/*
			//提示给登录用户
			ChartUser from = message.getFrom();
			message.setFrom(message.getAccept());
			message.setAccept(from);
			message.setMsg("[" + message.getFrom().getUserName()+"("+message.getFrom().getUserCode()+")" + "]未上线");
			ctx.channel().writeAndFlush(new TextWebSocketFrame(this.getMapper().writeValueAsString(message)));
		    */
			this.redisService.SendMsg(message);
		}
		
	}
}
