package fr.zng.xxzx.netty;

import fr.zng.xxzx.biz.SkSessionDto;
import fr.zng.xxzx.common.cacheData.ZngCacheData;
import fr.zng.xxzx.common.consts.FrBizConst;
import fr.zng.xxzx.common.util.CommUtil;
import fr.zng.xxzx.netty.dispatcher.InboundDispatcher;
import fr.zng.xxzx.util.ConvertUtil;
import fr.zng.xxzx.util.StringUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

import java.net.InetSocketAddress;

import javax.swing.JComponent;

public class InboundHandler extends ChannelInboundHandlerAdapter {

	// private static Log logger = LogFactory.getLog(InboundHandler1.class);
	// 读取接受的消息

	private JComponent jc;

	// 客户端ip地址
//	private String ip = "";

	public InboundHandler() {
	}

	public InboundHandler(JComponent jc) {
		this.jc = jc;
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		InetSocketAddress saddr = (InetSocketAddress) ctx.channel().remoteAddress();
		String ip = saddr.toString();
		// 将通道按ip地址存入map
		if (!ZngCacheData.sessionMap.containsKey(ip)) {
			SkSessionDto sd = new SkSessionDto();
			sd.setChannel(ctx.channel());
			sd.setTempstamp(System.currentTimeMillis());
			ZngCacheData.sessionMap.put(ip, sd);
		}
		CommUtil.doPrint(jc, "客户端连接 IP:", ip);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		InetSocketAddress saddr = (InetSocketAddress) ctx.channel().remoteAddress();
		String ip = saddr.toString();
		doFize(ctx);

		try {
			finalize();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		CommUtil.doPrint(jc, "客户端退出 IP:", ip);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		try {
			InetSocketAddress saddr = (InetSocketAddress) ctx.channel().remoteAddress();
			String ip = saddr.toString();
			ByteBuf result = (ByteBuf) msg;
			byte[] result1 = new byte[result.readableBytes()];
			result.readBytes(result1);
			 String data = ConvertUtil.bytesToHexString(result1,
			 result1.length).toUpperCase();
//			String data = new String(result1);
			CommUtil.doPrint(jc, "从客户端" + ip + "接收内容：", data);
			// 正常场合
			if (data.startsWith(FrBizConst.MKEY)) {
				// 分发处理
				new InboundDispatcher(jc, data, ip, ctx).dispatcher();
			}else{
				CommUtil.doPrint(jc, "从客户端" + ip ,"接收的内容不符合规范");
			}
		} finally {
			if (((ByteBuf) msg).refCnt() != 0) {
				ReferenceCountUtil.release(msg);
			}
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		InetSocketAddress saddr = (InetSocketAddress) ctx.channel().remoteAddress();
		String ip = saddr.toString();
		doFize(ctx);
		try {
			finalize();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		CommUtil.doPrint(jc, "客户端异常退出 IP:", ip);
		cause.printStackTrace();
		ctx.close();
	}
	
	
	public void doFize(ChannelHandlerContext ctx) {
		InetSocketAddress saddr = (InetSocketAddress) ctx.channel().remoteAddress();
		String ip = saddr.toString();
		// 移除
		// 通道关闭，移除map中ip
		ZngCacheData.sessionMap.remove(ip);
		// 根据ip获取设备号
		String code = ZngCacheData.sessionIPCode.get(ip);
		if (!StringUtil.isEmpty(code) && !"null".equals(code)) {
			// 设备号 + ip
			ZngCacheData.sessionCodeIP.remove(code);
			// ip + 设备号
			ZngCacheData.sessionIPCode.remove(ip);
			// 设备号 + 状态
			ZngCacheData.sessionDeviceStatus.remove(code);
			// 设备号 + 版本号
			ZngCacheData.sessionCodeVersion.remove(code);
			// 设备号 + 是否正在使用
			ZngCacheData.sessionWebCodeUsed.remove(code);
		}
	}
}
