package common.network;

import java.io.IOException;

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

public class PacketEncoder extends MessageToByteEncoder<Packet> {
	private final boolean client;

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

	protected void encode(ChannelHandlerContext context, Packet packet, ByteBuf output) throws IOException, Exception {
		Integer id = context.channel().attr(NetConnection.ATTR_STATE).get().getId(this.client, packet);
		if(id == null)
			throw new IOException("Kann nicht registriertes Paket nicht serialisieren");
		PacketBuffer pbuf = new PacketBuffer(output);
		pbuf.writeVarInt(id);
		try {
			packet.writePacketData(pbuf);
		}
		catch(Throwable t) {
			throw new IOException("Fehler beim Schreiben der Paketdaten", t);
		}
	}
}
