package common.network;

import java.util.List;

import common.net.buffer.ByteBuf;
import common.net.buffer.Unpooled;
import common.net.channel.ChannelHandlerContext;
import common.net.handler.codec.ByteToMessageDecoder;
import common.net.handler.codec.CorruptedFrameException;

public class PacketSplitter extends ByteToMessageDecoder {
	protected void decode(ChannelHandlerContext context, ByteBuf buffer, List<Object> output) throws Exception {
		buffer.markReaderIndex();
		byte[] data = new byte[3];
		for(int z = 0; z < data.length; z++) {
			if(!buffer.isReadable()) {
				buffer.resetReaderIndex();
				return;
			}
			data[z] = buffer.readByte();
			if(data[z] < 0)
				continue;
			PacketBuffer pbuf = new PacketBuffer(Unpooled.wrappedBuffer(data));
			try {
				int len = pbuf.readVarInt();
				if(buffer.readableBytes() >= len) {
					output.add(buffer.readBytes(len));
					return;
				}
				buffer.resetReaderIndex();
			}
			finally {
				pbuf.release();
			}
			return;
		}
		throw new CorruptedFrameException("length wider than 21-bit");
	}
}
