package com.ym.im.handler;

import com.ym.im.entity.HeartBeat;
import com.ym.im.entity.base.ChannelAttributeKey;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author: JJww
 * @Date:2020/11/6
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class HeartBeatServerHandler extends BaseHandler<HeartBeat> {

    private final static String PONG = "pong";

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                ctx.channel().close();
                log.info("用户: " + ctx.channel().attr(ChannelAttributeKey.ROLE_ID).get() + "  无心跳 ");
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HeartBeat heartBeat) throws Exception {
        ctx.channel().writeAndFlush(new TextWebSocketFrame(PONG));
    }
}
