package com.imdroid.beidou_fwd.service;

import com.imdroid.common.util.DataTypeUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Layton
 * @date 2023/2/18 20:36
 */
public class TcpMessageHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final TCPClient tcpClient;

    public TcpMessageHandler(TCPClient tcpClient) {
        this.tcpClient = tcpClient;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf buf) throws Exception {
        if (logger.isDebugEnabled()) {
            byte[] data = new byte[buf.readableBytes()];
            buf.getBytes(0, data);
            logger.debug("receive server message:" + DataTypeUtil.getHexString(data));
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("xfz tcp channel active");
        tcpClient.onConnected();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("xfz tcp channel inactive");
        tcpClient.onDisconnect();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("XFZTcpMessageHandler error: {}", cause.toString());
        ctx.close();
    }

}
