package com.pwt.netty.handler;

import com.pwt.netty.conponents.SocketChannelRepository;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
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;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author linyun
 * @version V1.0
 * @Title: NettyServerHeartHandler
 * @Description: 实现心跳的handler
 * @date 2022/11/04
 **/
@Slf4j
@Component
@ChannelHandler.Sharable
public class Vehicle2ServerHandler extends SimpleChannelInboundHandler<ByteBuf> {

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

    /**
     * 失败计数器：未收到client端发送的ping请求
     **/
    private int UN_REC_PING_TIMES = 0;

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

    @Autowired
    private SocketChannelRepository channelRepository;

    /**
     * @Description: 空闲触发器
     * @Author: linyun
     * @Date: 2022/11/4 9:04
     * @Param:[ctx, evt]
     * @Return:void
     **/
    @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 (UN_REC_PING_TIMES >= MAX_UN_REC_PING_TIMES)
            {
                // 连续超过N次未收到client的ping消息，那么关闭该通道，等待client重连
                ctx.channel().close();
            } else
            {
                // 失败计数器加1
                UN_REC_PING_TIMES++;
            }
//            log.debug(ctx.channel().remoteAddress() + "超时类型：" + type);
        } else
        {
            super.userEventTriggered(ctx, evt);
        }
    }

    /**
     * @Description: 客户端数据处理
     * @Author: linyun
     * @Date: 2022/11/8 11:04
     * @Param:[ctx, msg]
     * @Return:void
     **/
    @Override
    public void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception
    {
        /*if (CommandType.AUTH.getValue() == message.getCommand())
        {
            // 认证处理
            if ("pwt".equals(new String(message.getData())))
            {

            }
        } else if (CommandType.PING.getValue() == message.getCommand())
        {
            UN_REC_PING_TIMES = 0;
        } else
        {
            //触发下一个handler
            ctx.fireChannelRead(message);
        }
        ReferenceCountUtil.release(message);*/
    }

    /**
     * 客户端连接服务端的连接建立后调用
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception
    {
        log.info("连接成功...");
    }

    /**
     * 客户端主动断开服务端的链接,关闭流
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception
    {
        log.debug("客户端主动断开!!!");
        ctx.close();
    }

    /*
     * 发生异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
    {
        log.debug("发生异常:{}", cause.getMessage());
        cause.printStackTrace();
    }
}
