package common.packet;

import java.io.IOException;

import common.network.IPlayer;
import common.network.Packet;
import common.network.PacketBuffer;

public class CPacketForm implements Packet<IPlayer>
{
	private int id;
    private Object[] data;

    public CPacketForm()
    {
    }

    public CPacketForm(int id, Object[] data)
    {
    	this.id = id;
        this.data = data;
    }
    
    public void readPacketData(PacketBuffer buf) throws IOException
    {
    	this.id = buf.readVarInt();
        if(!buf.readBoolean()) {
        	this.data = null;
        	return;
        }
        this.data = new Object[buf.readVarInt()];
        for(int z = 0; z < this.data.length; z++) {
        	Object obj;
        	switch(buf.readByte()) {
        		case 0:
        			obj = buf.readBoolean();
        			break;
        		case 1:
        			obj = buf.readVarInt();
        			break;
        		default:
        			obj = buf.readString(1024);
        			break;
        	}
        	this.data[z] = obj;
        }
    }
    
    public void writePacketData(PacketBuffer buf) throws IOException
    {
    	buf.writeVarInt(this.id);
    	buf.writeBoolean(this.data != null);
        if(this.data == null)
        	return;
        buf.writeVarInt(this.data.length);
        for(int z = 0; z < this.data.length; z++) {
        	Object obj = this.data[z];
        	if(obj instanceof Boolean) {
        		buf.writeByte(0);
        		buf.writeBoolean((Boolean)obj);
        	}
        	else if(obj instanceof Integer) {
        		buf.writeByte(1);
        		buf.writeVarInt((Integer)obj);
        	}
        	else {
        		buf.writeByte(2);
        		buf.writeString((String)obj);
        	}
        }
    }
    
    public void processPacket(IPlayer handler)
    {
        handler.processForm(this);
    }

    public Object[] getData()
    {
        return this.data;
    }
    
    public int getId() {
    	return this.id;
    }
}
