package com.docus.server.common.netty.server.handler;

import com.docus.server.common.netty.Payload;
import com.docus.server.common.netty.server.ChannelRepository;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 客户端和服务端心跳
 */
@Slf4j
@ChannelHandler.Sharable
public class NettyHeartbeatHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Payload.Message message = (Payload.Message) msg;
        if (message.getCmd().equals(Payload.Message.type.HEARTBEAT_REQUEST)) {
            log.info("接收到客户端的心跳");
        } else {
            if (ctx.channel().isOpen()) {
                //触发下一个handler
                ctx.fireChannelRead(msg);
            }
        }
        ReferenceCountUtil.release(msg);
    }

    private ChannelRepository repository;

    public NettyHeartbeatHandler(ChannelRepository repository) {
        this.repository = repository;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                String clientId = repository.getClientKey(ctx.channel());
                //移除工控机缓存，设备离线
                repository.remove(clientId);
                log.info("{},关闭这个不活跃通道=================>", clientId);
                ctx.channel().close();
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        String clientId = repository.getClientKey(ctx.channel());
        log.error("通道发生异常，终端连接：{}", clientId);
        //移除工控机缓存，设备离线
        if (clientId != null) {
            repository.remove(clientId);
        }
        if (ctx.channel().isActive()) {
            ctx.close();
        }
        super.exceptionCaught(ctx, cause);
    }
}
