package com.pwt.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * @author linyun
 * @version V1.0
 * @Title: Vehicle2ClientHandler
 * @Description: 客户端心跳类
 * @date 2022/11/05
 **/
@Slf4j
public class Vehicle2ClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    // 定义客户端没有收到服务端的pong消息的最大次数
    private static final int MAX_UN_REC_PONG_TIMES = 3;

    // 客户端连续N次没有收到服务端的pong消息  计数器
    private int unRecPongTimes = 0;

    /**
     * 车辆临时VIN码
     **/
    private static final String TMP_VIN_CODE = "0123456789ABCDEFG";

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception
    {
        if (evt instanceof IdleStateEvent)
        {
            IdleStateEvent event = (IdleStateEvent) evt;
            String type = "";
            if (event.state() == IdleState.READER_IDLE)
            {
                type = "read idle";
            } else if (event.state() == IdleState.WRITER_IDLE)
            {
                type = "write idle";
            } else if (event.state() == IdleState.ALL_IDLE)
            {
                type = "all idle";
            }
            if (unRecPongTimes < MAX_UN_REC_PONG_TIMES)
            {
                // 发送心跳数据
                unRecPongTimes++;
            } else
            {
                ctx.channel().close();
            }

        } else
        {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception
    {
        // 认证回复
        /*if (CommandType.AUTH_BACK.getValue() == message.getCommand())
        {
            log.info("收到服务端认证回复数据:{}", new String(message.getData()));
            // 心跳回复
        } else if (message.getCommand() == CommandType.PING_BACK.getValue())
        {
            log.info("收到服务端心跳回复数据:{}", new String(message.getData()));
            unRecPongTimes = 0;
        }*/
    }

    // 连接成功后，向server发送认证消息
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception
    {
        log.info("开始发送认证数据...");
    }

    /**
     * 断开触发
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception
    {
        log.info("检测到心跳服务器断开！！！");
    }
}
