package net.minecraft.network.protocol.game;

import net.minecraft.core.Vec3i;
import net.minecraft.core.BlockPos;
import net.minecraft.network.PacketListener;
import java.io.IOException;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.network.protocol.Packet;

public class ClientboundChunkBlocksUpdatePacket implements Packet<ClientGamePacketListener> {
    private ChunkPos chunkPos;
    private BlockUpdate[] updates;
    
    public ClientboundChunkBlocksUpdatePacket() {
    }
    
    public ClientboundChunkBlocksUpdatePacket(final int integer, final short[] arr, final LevelChunk chj) {
        this.chunkPos = chj.getPos();
        this.updates = new BlockUpdate[integer];
        for (int integer2 = 0; integer2 < this.updates.length; ++integer2) {
            this.updates[integer2] = new BlockUpdate(arr[integer2], chj);
        }
    }
    
    @Override
    public void read(final FriendlyByteBuf mg) throws IOException {
        this.chunkPos = new ChunkPos(mg.readInt(), mg.readInt());
        this.updates = new BlockUpdate[mg.readVarInt()];
        for (int integer3 = 0; integer3 < this.updates.length; ++integer3) {
            this.updates[integer3] = new BlockUpdate(mg.readShort(), Block.BLOCK_STATE_REGISTRY.byId(mg.readVarInt()));
        }
    }
    
    @Override
    public void write(final FriendlyByteBuf mg) throws IOException {
        mg.writeInt(this.chunkPos.x);
        mg.writeInt(this.chunkPos.z);
        mg.writeVarInt(this.updates.length);
        for (final BlockUpdate a6 : this.updates) {
            mg.writeShort(a6.getOffset());
            mg.writeVarInt(Block.getId(a6.getBlock()));
        }
    }
    
    @Override
    public void handle(final ClientGamePacketListener nl) {
        nl.handleChunkBlocksUpdate(this);
    }
    
    public BlockUpdate[] getUpdates() {
        return this.updates;
    }
    
    public class BlockUpdate {
        private final short offset;
        private final BlockState block;
        
        public BlockUpdate(final short short2, final BlockState cfj) {
            this.offset = short2;
            this.block = cfj;
        }
        
        public BlockUpdate(final short short2, final LevelChunk chj) {
            this.offset = short2;
            this.block = chj.getBlockState(this.getPos());
        }
        
        public BlockPos getPos() {
            return new BlockPos(ClientboundChunkBlocksUpdatePacket.this.chunkPos.getBlockAt(this.offset >> 12 & 0xF, this.offset & 0xFF, this.offset >> 8 & 0xF));
        }
        
        public short getOffset() {
            return this.offset;
        }
        
        public BlockState getBlock() {
            return this.block;
        }
    }
}
