package net.minecraft.network;

import org.apache.logging.log4j.MarkerManager;
import org.apache.logging.log4j.LogManager;
import net.minecraft.network.protocol.Packet;
import java.io.IOException;
import io.netty.util.AttributeKey;
import java.util.List;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import net.minecraft.network.protocol.PacketFlow;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.Logger;
import io.netty.handler.codec.ByteToMessageDecoder;

public class PacketDecoder extends ByteToMessageDecoder {
    private static final Logger LOGGER;
    private static final Marker MARKER;
    private final PacketFlow flow;
    
    public PacketDecoder(final PacketFlow nj) {
        this.flow = nj;
    }
    
    protected void decode(final ChannelHandlerContext channelHandlerContext, final ByteBuf byteBuf, final List<Object> list) throws Exception {
        if (byteBuf.readableBytes() == 0) {
            return;
        }
        final FriendlyByteBuf mg5 = new FriendlyByteBuf(byteBuf);
        final int integer6 = mg5.readVarInt();
        final Packet<?> ni7 = ((ConnectionProtocol)channelHandlerContext.channel().attr((AttributeKey)Connection.ATTRIBUTE_PROTOCOL).get()).createPacket(this.flow, integer6);
        if (ni7 == null) {
            throw new IOException("Bad packet id " + integer6);
        }
        ni7.read(mg5);
        if (mg5.readableBytes() > 0) {
            throw new IOException("Packet " + ((ConnectionProtocol)channelHandlerContext.channel().attr((AttributeKey)Connection.ATTRIBUTE_PROTOCOL).get()).getId() + "/" + integer6 + " (" + ni7.getClass().getSimpleName() + ") was larger than I expected, found " + mg5.readableBytes() + " bytes extra whilst reading packet " + integer6);
        }
        list.add(ni7);
        if (PacketDecoder.LOGGER.isDebugEnabled()) {
            PacketDecoder.LOGGER.debug(PacketDecoder.MARKER, " IN: [{}:{}] {}", channelHandlerContext.channel().attr((AttributeKey)Connection.ATTRIBUTE_PROTOCOL).get(), integer6, ni7.getClass().getName());
        }
    }
    
    static {
        LOGGER = LogManager.getLogger();
        MARKER = MarkerManager.getMarker("PACKET_RECEIVED", Connection.PACKET_MARKER);
    }
}
