package com.imdroid.beidou.test_device.service.tcp;

import com.imdroid.beidou.test_device.service.OnlineChannels;
import com.imdroid.common.util.DataTypeUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@ChannelHandler.Sharable
@Component
public class RtcmTcpHandler extends SimpleChannelInboundHandler<ByteBuf> {
    private final Logger logger = LoggerFactory.getLogger(RtcmTcpServer.class);
    @Override
    public void channelActive(ChannelHandlerContext ctx){
        OnlineChannels.INSTANCE.updateChannel(ctx.channel().remoteAddress().toString(), ctx.channel());
    }
    @Override
    public void channelRead0(ChannelHandlerContext ctx, ByteBuf src) throws Exception{
        if (logger.isDebugEnabled()) {
            byte[] data = new byte[src.readableBytes()];
            src.getBytes(0, data);
            logger.debug("receive message:" + DataTypeUtil.getHexString(data));
        }
        try {
            OnlineChannels.INSTANCE.updateChannel(ctx.channel().remoteAddress().toString(), ctx.channel());
        }
        catch (Exception e){

        }
    }
/*
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;

            if (event.state() == IdleState.READER_IDLE) {
                Channel channel = ctx.channel();
                logger.info(channel.remoteAddress() + " idle too long to be closed");
                channel.close();
            }
        }
    }
*/
    @Override
    public void channelInactive(ChannelHandlerContext ctx)
            throws Exception {
        logger.info("channel inactive");
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

}