package com.cmvr.quic.gateway.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.junit.Assert;
import org.junit.Test;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class ControlFrameDecoderTest {

    @Test
    public void shouldDecodeFragmentedAndConsecutiveFrames() {
        ControlFrameDecoder decoder = new ControlFrameDecoder(1024);
        byte[] first = "register".getBytes(StandardCharsets.UTF_8);
        byte[] second = "heartbeat".getBytes(StandardCharsets.UTF_8);
        ByteBuf encoded = Unpooled.buffer();
        encoded.writeInt(first.length).writeBytes(first);
        encoded.writeInt(second.length).writeBytes(second);

        ByteBuf partOne = encoded.readRetainedSlice(3);
        ByteBuf partTwo = encoded.readRetainedSlice(encoded.readableBytes());
        try {
            Assert.assertTrue(decoder.append(partOne).isEmpty());
            List<byte[]> frames = decoder.append(partTwo);
            Assert.assertEquals(2, frames.size());
            Assert.assertArrayEquals(first, frames.get(0));
            Assert.assertArrayEquals(second, frames.get(1));
        } finally {
            partOne.release();
            partTwo.release();
            encoded.release();
        }
    }

    @Test(expected = IllegalArgumentException.class)
    public void shouldRejectOversizedFrame() {
        ControlFrameDecoder decoder = new ControlFrameDecoder(16);
        ByteBuf encoded = Unpooled.buffer().writeInt(17);
        try {
            decoder.append(encoded);
        } finally {
            encoded.release();
        }
    }
}
