package com.imdroid.sideslope.server.udp;

import com.imdroid.sideslope.exception.UnSupportedMessageException;
import com.imdroid.sideslope.executor.BizExecutors;
import com.imdroid.sideslope.executor.MessageParser;
import com.imdroid.sideslope.message.BaseMessage;
import com.imdroid.sideslope.server.OnlineChannels;
import com.imdroid.common.util.DataTypeUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author Layton
 * @date 2023/2/13 11:47
 */
@ChannelHandler.Sharable
@Component
public class RtcmUdpHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(RtcmUdpHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        DatagramPacket packet = (DatagramPacket) msg;
        try {
            if (packet.content() == null) {
                return;
            }
            if (logger.isDebugEnabled()) {
                byte[] data = new byte[packet.content().readableBytes()];
                packet.content().getBytes(0, data);
                logger.debug("receive message:" + DataTypeUtil.getHexString(data));
            }
            // 消息解析
            BaseMessage message = MessageParser.instance.parse(packet.content());
            OnlineChannels.INSTANCE.updateDataChannel(message.getId(), ctx.channel(), packet.sender());
            BizExecutors.execute(message);
        } catch (UnSupportedMessageException e) {
            logger.warn("receive un supported message: {}", e.getMessage());
        } catch (Exception e) {
            logger.error("channel read error: {}", e.toString());
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

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

}
