package common.packet;

import java.io.IOException;

import common.network.IClientPlayer;
import common.network.Packet;
import common.network.PacketBuffer;
import common.util.Triplet;

public class SPacketDisplayForm implements Packet<IClientPlayer>
{
	private int id;
	private String title;
    private Triplet<String, Object, Integer>[] data;

    public SPacketDisplayForm()
    {
    }

    public SPacketDisplayForm(int id, String title, Triplet<String, Object, Integer>[] data)
    {
    	this.id = id;
    	this.title = title;
        this.data = data;
    }

    public void processPacket(IClientPlayer handler)
    {
        handler.handleForm(this);
    }

    public void readPacketData(PacketBuffer buf) throws IOException
    {
    	this.id = buf.readVarInt();
    	this.title = buf.readString(256);
        this.data = new Triplet[buf.readVarInt()];
        for(int z = 0; z < this.data.length; z++) {
        	String name = buf.readString(64);
        	Object obj;
        	switch(buf.readByte()) {
        		case 0:
        			obj = buf.readBoolean();
        			break;
        		case 1:
        			String[] strs = new String[buf.readVarInt()];
        			obj = strs;
        			for(int n = 0; n < strs.length; n++) {
        				strs[n] = buf.readString(128);
        			}
        			break;
        		default:
        			obj = buf.readString(256);
        			break;
        	}
        	this.data[z] = new Triplet<String, Object, Integer>(name, obj, buf.readVarInt());
        }
    }

    public void writePacketData(PacketBuffer buf) throws IOException
    {
    	buf.writeVarInt(this.id);
    	buf.writeString(this.title);
        buf.writeVarInt(this.data.length);
        for(int z = 0; z < this.data.length; z++) {
        	buf.writeString(this.data[z].first());
        	Object obj = this.data[z].second();
        	if(obj instanceof Boolean) {
        		buf.writeByte(0);
        		buf.writeBoolean((Boolean)obj);
        	}
        	else if(obj instanceof String[]) {
        		buf.writeByte(1);
        		String[] strs = (String[])obj;
        		buf.writeVarInt(strs.length);
        		for(int n = 0; n < strs.length; n++) {
    				buf.writeString(strs[n]);
    			}
        	}
        	else {
        		buf.writeByte(2);
        		buf.writeString((String)obj);
        	}
        	buf.writeVarInt(this.data[z].third());
        }
    }

    public Triplet<String, Object, Integer>[] getData()
    {
        return this.data;
    }
    
    public String getTitle() {
    	return this.title;
    }
    
    public int getId() {
    	return this.id;
    }
}
