package com.artfess.base.webSocket;

import com.artfess.base.conf.NettyConfig;
import com.artfess.base.util.AppUtil;
import com.artfess.base.util.StringUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 陈实
 * @Package com.artfess.base.webSocket
 * @date 2021/9/16 9:59
 * @Description:心跳包测试处理类
 */
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {
    private static final Logger log = LoggerFactory.getLogger(HeartBeatHandler.class);
    private int lossConnectCount = 0;

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        SubroutineManage subroutineManage = AppUtil.getBean(SubroutineManage.class);
        if (evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent)evt;
            if (event.state()== IdleState.READER_IDLE){
                log.warn("读空闲");
            }else if(event.state()==IdleState.WRITER_IDLE){
                log.warn("写空闲");
            }else if(event.state()==IdleState.ALL_IDLE){
                log.warn("读写都空闲你，关闭通道");
                lossConnectCount ++;
                if (lossConnectCount > 5){
                    //修改子程序的在线状态
                    /*String message = NettyConfig.getSubroutineChanIdMap().get(ctx.channel().id().asShortText());
                    if(StringUtil.isNotEmpty(message)){
                        subroutineManage.updateStatusByHeartbeat(message,"NONE");
                    }*/

                    NettyConfig.getSubroutineChanIdMap().remove(ctx.channel().id().asShortText());
                    ctx.channel().close();
                }
            }
        }else {
            super.userEventTriggered(ctx,evt);
        }
    }

}
