package common.packet;

import java.io.IOException;

import common.item.ItemStack;
import common.network.IClientPlayer;
import common.network.Packet;
import common.network.PacketBuffer;
import common.village.MerchantRecipe;
import common.village.MerchantRecipeList;

public class SPacketTrades implements Packet<IClientPlayer>
{
    private MerchantRecipeList recipes;
    private int windowId;

    public SPacketTrades()
    {
    }

    public SPacketTrades(MerchantRecipeList recipesIn, int windowIdIn)
    {
        this.recipes = recipesIn;
        this.windowId = windowIdIn;
    }

    /**
     * Reads the raw packet data from the data stream.
     */
    public void readPacketData(PacketBuffer buf) throws IOException
    {
    	this.windowId = buf.readInt();
    	this.recipes = new MerchantRecipeList();
        int i = buf.readByte() & 255;

        for (int j = 0; j < i; ++j)
        {
            ItemStack itemstack = buf.readItemStack();
            ItemStack itemstack1 = buf.readItemStack();
            ItemStack itemstack2 = null;

            if (buf.readBoolean())
            {
                itemstack2 = buf.readItemStack();
            }

//            boolean flag = buf.readBoolean();
//            int k = buf.readInt();
//            int l = buf.readInt();
            MerchantRecipe merchantrecipe = new MerchantRecipe(itemstack, itemstack2, itemstack1); // , k, l);

//            if (flag)
//            {
//                merchantrecipe.compensateToolUses();
//            }

            this.recipes.add(merchantrecipe);
        }
    }

    /**
     * Writes the raw packet data to the data stream.
     */
    public void writePacketData(PacketBuffer buf) throws IOException
    {
    	buf.writeInt(this.windowId);
    	buf.writeByte((byte)(this.recipes.size() & 255));

        for (int i = 0; i < this.recipes.size(); ++i)
        {
            MerchantRecipe merchantrecipe = (MerchantRecipe)this.recipes.get(i);
            buf.writeItemStack(merchantrecipe.first());
            buf.writeItemStack(merchantrecipe.result());
            ItemStack itemstack = merchantrecipe.second();
            buf.writeBoolean(itemstack != null);

            if (itemstack != null)
            {
            	buf.writeItemStack(itemstack);
            }

//            buf.writeBoolean(merchantrecipe.isRecipeDisabled());
//            buf.writeInt(merchantrecipe.getToolUses());
//            buf.writeInt(merchantrecipe.getMaxTradeUses());
        }
    }

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

    public MerchantRecipeList getTrades()
    {
        return this.recipes;
    }

    public int getWindowId()
    {
        return this.windowId;
    }
}
