package common.network;

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

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class PacketDecoder extends ByteToMessageDecoder
{
    private final boolean client;

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

    protected void decode(ChannelHandlerContext p_decode_1_, ByteBuf p_decode_2_, List<Object> p_decode_3_) throws IOException, InstantiationException, IllegalAccessException, Exception
    {
        if (p_decode_2_.readableBytes() != 0)
        {
            PacketBuffer packetbuffer = new PacketBuffer(p_decode_2_);
            int i = packetbuffer.readVarIntFromBuffer();
            Packet packet = ((PacketRegistry)p_decode_1_.channel().attr(NetConnection.ATTR_STATE).get()).getPacket(this.client, i);

            if (packet == null)
            {
                throw new IOException("Ungültige Paket-ID " + i);
            }
            else
            {
                packet.readPacketData(packetbuffer);

                if (packetbuffer.readableBytes() > 0)
                {
                    throw new IOException("Paket " + ((PacketRegistry)p_decode_1_.channel().attr(NetConnection.ATTR_STATE).get()).ordinal() + "/" + i + " (" + packet.getClass() + ") war größer als erwartet, " + packetbuffer.readableBytes() + " weitere Bytes wurden beim Lesen von Paket " + i + " gefunden");
                }
                else
                {
                    p_decode_3_.add(packet);

//                    if (Log.isTraceEnabled())
//                    {
//                         Log.SYSTEM.info("EIN: [" + p_decode_1_.channel().attr(NetConnection.ATTR_STATE).get() + ":" + i + "] " + packet.getClass().getName());
//                    }
                }
            }
        }
    }
}
