package common.network;

import java.io.IOException;
import java.util.List;

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

public class PacketDecoder extends ByteToMessageDecoder {
	private final boolean client;

	public PacketDecoder(boolean client) {
		this.client = client;
	}

	protected void decode(ChannelHandlerContext context, ByteBuf buffer, List<Object> output) throws IOException, InstantiationException, IllegalAccessException, Exception {
		if(buffer.readableBytes() == 0)
			return;
		PacketBuffer pbuf = new PacketBuffer(buffer);
		int id = pbuf.readVarInt();
		Packet packet = context.channel().attr(NetConnection.ATTR_STATE).get().getPacket(this.client, id);
		if(packet == null)
			throw new IOException("Ungültige Paket-ID " + id);
		packet.readPacketData(pbuf);
		if(pbuf.readableBytes() > 0)
			throw new IOException("Paket " + ((PacketRegistry)context.channel().attr(NetConnection.ATTR_STATE).get()).ordinal() + "/" + id + " ("
					+ packet.getClass() + ") war größer als erwartet, " + pbuf.readableBytes() + " weitere Bytes wurden beim Lesen von Paket " + id + " gefunden");
		output.add(packet);
	}
}
