package com.imdroid.beidou_fwd.service;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;

/**
 * @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 {
        String msg = buf.toString(Charset.defaultCharset());
        tcpClient.onMessage(msg);
        if (logger.isDebugEnabled()) {
            logger.debug("receive server message:" + msg);
        }
    }

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

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

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

}
