package com.cmvr.quic.gateway.server;

import com.cmvr.quic.edge.v1.EdgeControlEnvelope;
import com.cmvr.quic.gateway.core.ConnectionSession;
import com.cmvr.quic.gateway.protocol.ControlFrameDecoder;
import com.google.protobuf.InvalidProtocolBufferException;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;

/** 解析客户端发起的唯一可靠双向控制流。 */
final class ControlStreamHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private final ConnectionSession session;
    private final ControlFrameDecoder decoder;

    ControlStreamHandler(ConnectionSession session, int maximumControlFrameBytes) {
        this.session = session;
        this.decoder = new ControlFrameDecoder(maximumControlFrameBytes);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext context, ByteBuf input) {
        final List<byte[]> frames;
        try {
            frames = decoder.append(input);
        } catch (IllegalArgumentException error) {
            session.protocolViolation(error.getMessage(), 0);
            return;
        }
        for (byte[] frame : frames) {
            try {
                session.process(EdgeControlEnvelope.parseFrom(frame));
            } catch (InvalidProtocolBufferException error) {
                session.protocolViolation("无法解析EdgeControlEnvelope", 0);
                return;
            } catch (RuntimeException error) {
                session.fail("处理QUIC控制消息失败", error);
                return;
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
        session.fail("QUIC控制流异常", cause);
    }
}
