package common.packet;

import java.io.IOException;

import common.network.IClientPlayer;
import common.network.Packet;
import common.network.PacketBuffer;
import common.util.BlockPos;
import common.util.ChunkPos;
import common.world.State;

public class SPacketMultiBlockChange implements Packet<IClientPlayer>
{
    private ChunkPos chunkPosCoord;
    private SPacketMultiBlockChange.BlockUpdateData[] changedBlocks;

    public static BlockPos getPos(ChunkPos pos, long position)
    {
		return new BlockPos(new BlockPos((pos.x << 4) + (int)(position >> 36 & 15L), (int)(position & 4294967295L), (pos.z << 4) + (int)(position >> 32 & 15L)));
    }

    public SPacketMultiBlockChange()
    {
    }
    
    public SPacketMultiBlockChange(ChunkPos pos, SPacketMultiBlockChange.BlockUpdateData[] changes) {
    	this.chunkPosCoord = pos;
    	this.changedBlocks = changes;
    }

    /**
     * Reads the raw packet data from the data stream.
     */
    public void readPacketData(PacketBuffer buf) throws IOException
    {
        this.chunkPosCoord = new ChunkPos(buf.readInt(), buf.readInt());
        this.changedBlocks = new SPacketMultiBlockChange.BlockUpdateData[buf.readVarInt()];

        for (int i = 0; i < this.changedBlocks.length; ++i)
        {
            this.changedBlocks[i] = new SPacketMultiBlockChange.BlockUpdateData(buf.readLong(), (State)State.ID_MAP.getByValue(buf.readVarInt()));
        }
    }

    /**
     * Writes the raw packet data to the data stream.
     */
    public void writePacketData(PacketBuffer buf) throws IOException
    {
        buf.writeInt(this.chunkPosCoord.x);
        buf.writeInt(this.chunkPosCoord.z);
        buf.writeVarInt(this.changedBlocks.length);

        for (SPacketMultiBlockChange.BlockUpdateData s22packetmultiblockchange$blockupdatedata : this.changedBlocks)
        {
            buf.writeLong(s22packetmultiblockchange$blockupdatedata.getRawPos());
            buf.writeVarInt(State.ID_MAP.get(s22packetmultiblockchange$blockupdatedata.getBlockState()));
        }
    }

    /**
     * Passes this Packet on to the NetHandler for processing.
     */
    public void processPacket(IClientPlayer handler)
    {
        handler.handleMultiBlockChange(this);
    }

    public SPacketMultiBlockChange.BlockUpdateData[] getChangedBlocks()
    {
        return this.changedBlocks;
    }

    public ChunkPos getChunkPos()
    {
        return this.chunkPosCoord;
    }

    public static class BlockUpdateData
    {
        private final long position;
        private final State blockState;

        public BlockUpdateData(long raw, State state)
        {
            this.position = raw;
            this.blockState = state;
        }
        
        public long getRawPos()
        {
            return this.position;
        }

        public State getBlockState()
        {
            return this.blockState;
        }
    }
}
