package common.packet;

import java.io.IOException;
import common.network.IClientPlayer;
import common.network.Packet;
import common.network.PacketBuffer;

public class SPacketChunkData implements Packet<IClientPlayer>
{
    private int chunkX;
    private int chunkZ;
    private SPacketChunkData.Extracted extractedData;
    private boolean biomes;

    public SPacketChunkData()
    {
    }

    public SPacketChunkData(int x, int z, boolean biomes, SPacketChunkData.Extracted data)
    {
        this.chunkX = x;
        this.chunkZ = z;
        this.biomes = biomes;
        this.extractedData = data;
    }

    /**
     * Reads the raw packet data from the data stream.
     */
    public void readPacketData(PacketBuffer buf) throws IOException
    {
        this.chunkX = buf.readInt();
        this.chunkZ = buf.readInt();
        this.biomes = buf.readBoolean();
        this.extractedData = new SPacketChunkData.Extracted();
        this.extractedData.data = buf.readByteArray();
        this.extractedData.extend = new int[buf.readVarInt()];
        for(int z = 0; z < this.extractedData.extend.length; z++) {
        	this.extractedData.extend[z] = buf.readVarInt();
        }
    }

    /**
     * Writes the raw packet data to the data stream.
     */
    public void writePacketData(PacketBuffer buf) throws IOException
    {
        buf.writeInt(this.chunkX);
        buf.writeInt(this.chunkZ);
        buf.writeBoolean(this.biomes);
        buf.writeByteArray(this.extractedData.data);
        buf.writeVarInt(this.extractedData.extend.length);
        for(int z = 0; z < this.extractedData.extend.length; z++) {
        	buf.writeVarInt(this.extractedData.extend[z]);
        }
    }

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

    public byte[] getExtractedDataBytes()
    {
        return this.extractedData.data;
    }

    public static int getSize(int segments, boolean overworld, boolean biomes)
    {
        int i = segments * 2 * 16 * 16 * 16;
        int j = segments * 16 * 16 * 16 / 2;
        int k = overworld ? segments * 16 * 16 * 16 / 2 : 0;
        int l = biomes ? 256 : 0;
        return i + j + k + l;
    }

    public int getChunkX()
    {
        return this.chunkX;
    }

    public int getChunkZ()
    {
        return this.chunkZ;
    }
    
    public int[] getExtractedExtend()
    {
        return this.extractedData.extend;
    }

    public boolean hasBiomes()
    {
        return this.biomes;
    }

    public static class Extracted
    {
        public byte[] data;
        public int[] extend;
    }
}
