package common.network;

import java.io.IOException;

import common.log.Log;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

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

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

    protected void encode(ChannelHandlerContext p_encode_1_, Packet p_encode_2_, ByteBuf p_encode_3_) throws IOException, Exception
    {
        Integer integer = ((PacketRegistry)p_encode_1_.channel().attr(NetConnection.ATTR_STATE).get()).getId(this.client, p_encode_2_);

//        if (Log.isTraceEnabled())
//        {
//        	Log.debug("AUS: [" + p_encode_1_.channel().attr(NetConnection.ATTR_STATE).get() + ":" + integer + "] " + p_encode_2_.getClass().getName());
//        }

        if (integer == null)
        {
            throw new IOException("Kann nicht registriertes Paket nicht serialisieren");
        }
        else
        {
            PacketBuffer packetbuffer = new PacketBuffer(p_encode_3_);
            packetbuffer.writeVarIntToBuffer(integer.intValue());

            try
            {
                p_encode_2_.writePacketData(packetbuffer);
            }
            catch (Throwable throwable)
            {
            	Log.JNI.error(throwable, "Fehler beim Schreiben der Paketdaten");
            }
        }
    }
}
