package com.pingpang.websocketchat.send.impl;

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

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.ChatGroup;
import com.pingpang.websocketchat.Message;
import com.pingpang.websocketchat.send.ChatSend;

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

public class ChatSendGroup extends ChatSend {

	@Override
	public void send(Message message, ChannelHandlerContext ctx) throws JsonProcessingException {
        
		if(StringUtil.isNUll(message.getGroup().getGroupCode())) {
			return;
		}
		
		message.getFrom().setUserPassword("");
		message.setFrom(userService.getUser(message.getFrom()));

		Map<String,String> queryMap=new HashMap<String,String>();
		queryMap.put("groupCode",message.getGroup().getGroupCode());
	    ChatGroup group=this.userGroupService.getGroup(queryMap);
	    
	    if(!"0".equals(group.getGroupStatus())) {
			ctx.writeAndFlush(new TextWebSocketFrame(this.getMapper().writeValueAsString(getAdmessag("群已被封闭["+message.getGroup().getGroupCode()+"]!","2"))));
		    return;
	    }
	    
	    message.setGroup(group);
		
		if (!ChannelManager.isExit(message.getGroup(), message.getFrom().getUserCode())) {
			ctx.writeAndFlush(new TextWebSocketFrame(this.getMapper().writeValueAsString(getAdmessag("你已退群["+message.getGroup().getGroupCode()+"]!","2"))));
		    return;
		}
		
        if(null!=ctx) {
        	
		 Set<ChartUser> user = ChannelManager.getGroupUser(message.getGroup());
		 for (ChartUser str : user) {
			str.setUserPassword("");
			message.setAccept(userService.getUser(str));// 添加接收方数据
			
			//自己和自己不用发送信息
			if(str.equals(message.getFrom())){
				message.setStatus("1");
				userMsgService.addMsg(message);
			}else if (!str.equals(message.getFrom()) && ChannelManager.isExitChannel(str)) {
				ChannelManager.getChannel(str.getUserCode())
						.writeAndFlush(new TextWebSocketFrame(this.getMapper().writeValueAsString(message)));
				message.setStatus("1");
				userMsgService.addMsg(message);
			}else if(!ChannelManager.isExitChannel(str)) {
				message.setStatus("0");
				userMsgService.addMsg(message);//看下ID是否会回显
				this.sendOtherServerMsg(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); 
        	ChannelManager.getChannel(message.getAccept().getUserCode())
			.writeAndFlush(new TextWebSocketFrame(this.getMapper().writeValueAsString(message)));
        }
	}
}
