package com.pingpang.websocketchat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;

/**
 * 说明：心跳服务器处理器
 */
public class HeartbeatServerHandler extends ChannelInboundHandlerAdapter {
	
	// Return a unreleasable view on the given ByteBuf
	// which will just ignore release and retain calls.
	private int count=0;
	private static final ByteBuf HEARTBEAT_SEQUENCE = Unpooled
			.unreleasableBuffer(Unpooled.copiedBuffer("Heartbeat",
					CharsetUtil.UTF_8));  

	//日志操作
    private Logger logger = LoggerFactory.getLogger(HeartbeatServerHandler.class);
	
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent event = (IdleStateEvent) evt;
			logger.info(ctx.channel().remoteAddress()+"超时次数:"+count);
			String type = "";
			if (event.state() == IdleState.READER_IDLE) {
				type = "read idle";
				count++;
				if(count>5) {
					  logger.info("超时次数达到最大值了，断开连接");
		              ChannelManager.removeChannelByChannel(ctx.channel());
		              ctx.channel().close();
					}
			} else if (event.state() == IdleState.WRITER_IDLE) {
				type = "write idle";
				count=0;
			} else if (event.state() == IdleState.ALL_IDLE) {
				type = "all idle";
				count=0;
			}
			ctx.writeAndFlush(new TextWebSocketFrame("Heartbeat")).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
			logger.info( ctx.channel().remoteAddress()+"超时类型：" + type);
		}
		super.userEventTriggered(ctx, evt);
	}
}
