package com.pingpang.websocketchat.send.impl;

import java.io.File;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.pingpang.image.VideoUtil;
import com.pingpang.redis.RedisPre;
import com.pingpang.util.StringUtil;
import com.pingpang.websocketchat.ChannelManager;
import com.pingpang.websocketchat.ChartUser;
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 ChatSendAudioLive extends ChatSend {

	@Override
	public void send(Message message, ChannelHandlerContext ctx) throws Exception {
       
		    Set<String> msg=new HashSet<String>();
		    msg.add("regist");//添加直播间
			msg.add("query");//查询所有直播间信息
			msg.add("close");//关闭直播间
			msg.add("in");//进入直播间  暂用group处理
			msg.add("out");//离开直播间 暂用group处理
			msg.add("send");//发送数据处理 用这个命令
			logger.info("{}直播当前子指令{}",message.getFrom().getUserCode(),message.getCmdChild());
			if(!msg.contains(message.getCmdChild())){
				logger.info("IP:{},用户:{},对方用户:{}多媒体错误信息{}",ctx.channel().remoteAddress(),message.getFrom().getUserCode(),message.getAccept().getUserCode(),message.getMsg());
				return;
			}
			
			//注册信息
			if("regist".equals(message.getCmdChild())) {
				ChartUser cu=this.userService.getUser(message.getFrom());
				cu.setUserStatus("");
				cu.setLiveType("0");//webrtc 方式
				this.redisService.addSet(RedisPre.AUDIO_LIVE_SET+message.getFrom().getUserCode(),cu);
				return;
			}
			
			//注册信息
			if("query".equals(message.getCmdChild())) {
				Set<String> liveSet=this.redisService.getSetPrex(RedisPre.AUDIO_LIVE_SET+"*");
				Set<ChartUser> cuLiveSet=new HashSet<ChartUser>();
				for(String str:liveSet) {
					ChartUser cu=new ChartUser();
					cu.setUserCode(str.substring(RedisPre.AUDIO_LIVE_SET.length()));
					
					/**
					 * 这里做的有点不合理 因为要区分是webrtc过来还是flv过来得暂且先这样
					 */
					Set<ChartUser> liveUserSet=(Set<ChartUser>)(Set<?>)this.redisService.getSet(RedisPre.AUDIO_LIVE_SET+cu.getUserCode());
                    for(ChartUser currentCu: liveUserSet) {
                    	if(currentCu.getUserCode().equals(cu.getUserCode())) {
                    		cuLiveSet.add(currentCu);  
                    		break;
                    	}
                    }
				    	
				}
				
				message.setChatSet(cuLiveSet);
				ctx.channel().writeAndFlush(new TextWebSocketFrame(this.getMapper().writeValueAsString(message)));
				return;
			}
			
			
			//进入直播间
		if ("in".equals(message.getCmdChild()) || "out".equals(message.getCmdChild())
				|| "close".equals(message.getCmdChild()) || "send".equals(message.getCmdChild())) {
			if (StringUtil.isNUll(message.getGroup().getGroupCode())) {
				return;
			}
			ChartUser cu = this.userService.getUser(message.getFrom());
			cu.setUserStatus("");
			message.setFrom(cu);

			if ("in".equals(message.getCmdChild())) {
				this.redisService.addSet(RedisPre.AUDIO_LIVE_SET + message.getGroup().getGroupCode(), cu);
			}
			
			if("out".equals(message.getCmdChild())) {
				this.redisService.removeSet(RedisPre.AUDIO_LIVE_SET + message.getGroup().getGroupCode(), cu);
			}
			
			Set<ChartUser> liveUserSet = (Set<ChartUser>) (Set<?>) this.redisService
					.getSet(RedisPre.AUDIO_LIVE_SET + message.getGroup().getGroupCode());

			// 获取数据后清理直播间
			if ("close".equals(message.getCmdChild())) {
				this.redisService.deletePrex(RedisPre.AUDIO_LIVE_SET + message.getFrom().getUserCode());
			}
			//当前由用户了才发送转码数据 直播的时候用户会注册进来 size=1
			if("send".equals(message.getCmdChild()) && liveUserSet.size()>1) {
				//视频路径
				String videoPath=PATH +message.getFrom().getUserCode()+"_"+message.getAccept().getUserCode()+File.separator;
				//处理视频信息
				String base64Video=message.getMsg();
				String fileName=UUID.randomUUID().toString().replace("-", "")+".webm";
				try {
				  String magicVideo=VideoUtil.getChangeVideoBase64(base64Video,videoPath+fileName,videoPath,".webm");
				  magicVideo=base64Video.substring(0,base64Video.indexOf(";base64,"))+";base64,"+magicVideo;
				  message.setMsg(magicVideo);
				}catch(Exception e) {
					logger.info("视频{}->{}处理失败",message.getFrom().getUserCode(),message.getAccept().getUserCode());
					logger.error(e.getMessage(),e);
				}
			}
			
			for (ChartUser liveCu : liveUserSet) {
				liveCu.setUserPassword("");
				message.setAccept(userService.getUser(liveCu));// 添加接收方数据

				if ("in".equals(message.getCmdChild())) {
					message.setMsg(message.getFrom().getUserName() + "(" + message.getFrom().getUserCode() + ")进入直播间");
				} else if ("out".equals(message.getCmdChild())) {
					message.setMsg(message.getFrom().getUserName() + "(" + message.getFrom().getUserCode() + ")离开直播间");
				} else if ("close".equals(message.getCmdChild())) {
					message.setMsg(message.getFrom().getUserName() + "(" + message.getFrom().getUserCode() + ")直播结束");
				}

				if (!"send".equals(message.getCmdChild())) {
					if (ChannelManager.isExitChannel(liveCu)) {
						ChannelManager.getChannel(liveCu.getUserCode())
								.writeAndFlush(new TextWebSocketFrame(this.getMapper().writeValueAsString(message)));
					} else if (!ChannelManager.isExitChannel(liveCu)) {
						this.sendOtherServerMsg(message);
					}
				}else {
					if(!liveCu.getUserCode().equals(message.getFrom().getUserCode())) {
						if (ChannelManager.isExitChannel(liveCu)) {
							ChannelManager.getChannel(liveCu.getUserCode())
									.writeAndFlush(new TextWebSocketFrame(this.getMapper().writeValueAsString(message)));
						} else if (!ChannelManager.isExitChannel(liveCu)) {
							this.sendOtherServerMsg(message);
						}
					}
				}
			}
			return;
		}
	}
}
