package common.inventory;

import java.util.List;

import common.enchantment.Enchantment;
import common.enchantment.EnchantmentHelper;
import common.enchantment.RngEnchantment;
import common.entity.npc.EntityNPC;
import common.init.Blocks;
import common.init.Items;
import common.item.ItemStack;
import common.rng.Random;
import common.util.BlockPos;
import common.util.Pair;
import common.world.World;

public class ContainerEnchantment extends Container
{
    public IInventory table;
    private World world;
    private BlockPos position;
    private Random rand;
    public int seed;
    public int[] mana;
    public Pair<Enchantment, Integer>[] ench;

    public ContainerEnchantment(InventoryPlayer playerInv, World worldIn)
    {
        this(playerInv, worldIn, BlockPos.ORIGIN);
    }

    public ContainerEnchantment(InventoryPlayer playerInv, World worldIn, BlockPos pos)
    {
        this.table = new InventoryBasic("Enchant", true, 1)
        {
            public int getInventoryStackLimit()
            {
                return ItemStack.MAX_SIZE;
            }
            public void markDirty()
            {
                super.markDirty();
                ContainerEnchantment.this.onCraftMatrixChanged(this);
            }
        };
        this.rand = new Random();
        this.mana = new int[3];
        this.ench = new Pair[] {null, null, null};
        this.world = worldIn;
        this.position = pos;
        this.seed = playerInv.player.getEnchSeed();
        this.addSlotToContainer(new Slot(this.table, 0, 25, 47)
        {
            public boolean isItemValid(ItemStack stack)
            {
                return true;
            }
            public int getSlotStackLimit()
            {
                return 1;
            }
        });

        for (int i = 0; i < 3; ++i)
        {
            for (int j = 0; j < 9; ++j)
            {
                this.addSlotToContainer(new Slot(playerInv, j + i * 9 + 9, 8 + j * 18, 84 + i * 18));
            }
        }

        for (int k = 0; k < 9; ++k)
        {
            this.addSlotToContainer(new Slot(playerInv, k, 8 + k * 18, 142));
        }
    }
    
    public static int encodeData(Pair<Enchantment, Integer> data) {
    	return data == null ? -1 : data.first().ordinal() | data.second() << 8;
    }
    
    public static Pair<Enchantment, Integer> decodeData(int data) {
    	return data < 0 ? null : new Pair<Enchantment, Integer>(Enchantment.values()[(data & 0xff) % Enchantment.values().length], data >> 8);
    }

    public void onCraftGuiOpened(ICrafting listener)
    {
        super.onCraftGuiOpened(listener);
        listener.sendProgressBarUpdate(this, 0, this.mana[0]);
        listener.sendProgressBarUpdate(this, 1, this.mana[1]);
        listener.sendProgressBarUpdate(this, 2, this.mana[2]);
        listener.sendProgressBarUpdate(this, 3, this.seed & -16);
        listener.sendProgressBarUpdate(this, 4, encodeData(this.ench[0]));
        listener.sendProgressBarUpdate(this, 5, encodeData(this.ench[1]));
        listener.sendProgressBarUpdate(this, 6, encodeData(this.ench[2]));
    }

    public void detectAndSendChanges()
    {
        super.detectAndSendChanges();

        for (int i = 0; i < this.crafters.size(); ++i)
        {
            ICrafting icrafting = (ICrafting)this.crafters.get(i);
            icrafting.sendProgressBarUpdate(this, 0, this.mana[0]);
            icrafting.sendProgressBarUpdate(this, 1, this.mana[1]);
            icrafting.sendProgressBarUpdate(this, 2, this.mana[2]);
            icrafting.sendProgressBarUpdate(this, 3, this.seed & -16);
            icrafting.sendProgressBarUpdate(this, 4, encodeData(this.ench[0]));
            icrafting.sendProgressBarUpdate(this, 5, encodeData(this.ench[1]));
            icrafting.sendProgressBarUpdate(this, 6, encodeData(this.ench[2]));
        }
    }

    public void updateProgressBar(int id, int data)
    {
        if (id >= 0 && id <= 2)
        {
            this.mana[id] = data;
        }
        else if (id == 3)
        {
            this.seed = data;
        }
        else if (id >= 4 && id <= 6)
        {
            this.ench[id - 4] = decodeData(data);
        }
        else
        {
            super.updateProgressBar(id, data);
        }
    }

    public void onCraftMatrixChanged(IInventory inventoryIn)
    {
        if (inventoryIn == this.table)
        {
            ItemStack itemstack = inventoryIn.getStackInSlot(0);

            if (itemstack != null && itemstack.isItemEnchantable())
            {
                if (!this.world.client)
                {
                    int l = 0;

                    for (int j = -1; j <= 1; ++j)
                    {
                        for (int k = -1; k <= 1; ++k)
                        {
                            if ((j != 0 || k != 0) && this.world.isAirBlock(this.position.add(k, 0, j)) && this.world.isAirBlock(this.position.add(k, 1, j)))
                            {
                                if (this.world.getState(this.position.add(k * 2, 0, j * 2)).getBlock() == Blocks.bookshelf)
                                {
                                    ++l;
                                }

                                if (this.world.getState(this.position.add(k * 2, 1, j * 2)).getBlock() == Blocks.bookshelf)
                                {
                                    ++l;
                                }

                                if (k != 0 && j != 0)
                                {
                                    if (this.world.getState(this.position.add(k * 2, 0, j)).getBlock() == Blocks.bookshelf)
                                    {
                                        ++l;
                                    }

                                    if (this.world.getState(this.position.add(k * 2, 1, j)).getBlock() == Blocks.bookshelf)
                                    {
                                        ++l;
                                    }

                                    if (this.world.getState(this.position.add(k, 0, j * 2)).getBlock() == Blocks.bookshelf)
                                    {
                                        ++l;
                                    }

                                    if (this.world.getState(this.position.add(k, 1, j * 2)).getBlock() == Blocks.bookshelf)
                                    {
                                        ++l;
                                    }
                                }
                            }
                        }
                    }

                    this.rand.setSeed((long)this.seed);

                    for (int i1 = 0; i1 < 3; ++i1)
                    {
                        this.mana[i1] = EnchantmentHelper.calcItemStackEnchantability(this.rand, i1, l, itemstack);
                        this.ench[i1] = null;

                        if (this.mana[i1] < i1 + 1)
                        {
                            this.mana[i1] = 0;
                        }
                    }

                    for (int j1 = 0; j1 < 3; ++j1)
                    {
                        if (this.mana[j1] > 0)
                        {
                            List<RngEnchantment> list = this.getRandomEnchantments(itemstack, j1, this.mana[j1]);

                            if (list != null && !list.isEmpty())
                            {
                                RngEnchantment enchantmentdata = (RngEnchantment)list.get(this.rand.zrange(list.size()));
                                this.ench[j1] = new Pair<Enchantment, Integer>(enchantmentdata.enchantment, enchantmentdata.level);
                            }
                        }
                    }

                    this.detectAndSendChanges();
                }
            }
            else
            {
                for (int i = 0; i < 3; ++i)
                {
                    this.mana[i] = 0;
                    this.ench[i] = null;
                }
            }
        }
    }

	public boolean enchantItem(EntityNPC player, int id) {
		ItemStack stack = this.table.getStackInSlot(0);
		int cost = id + 1;

		if(this.mana[id] > 0 && stack != null && player.getManaPoints() >= cost && player.getManaPoints() >= this.mana[id]) {
			if(!this.world.client) {
				List<RngEnchantment> ench = this.getRandomEnchantments(stack, id, this.mana[id]);
				boolean book = stack.getItem() == Items.book;

				if(ench != null) {
					player.useMana(cost);
					player.updateEnchSeed();

					if(book)
						stack.setItem(Items.enchanted_book);

					for(int z = 0; z < ench.size(); z++) {
						RngEnchantment itm = ench.get(z);

						if(book)
							Items.enchanted_book.addEnchantment(stack, itm);
						else
							stack.addEnchantment(itm.enchantment, itm.level);
					}

					this.table.markDirty();
					this.seed = player.getEnchSeed();
					this.onCraftMatrixChanged(this.table);
				}
			}

			return true;
		}
		else {
			return false;
		}
	}

    private List<RngEnchantment> getRandomEnchantments(ItemStack stack, int id, int level)
    {
        this.rand.setSeed((long)(this.seed + id));
        List<RngEnchantment> list = EnchantmentHelper.buildEnchantmentList(this.rand, stack, level);

        if (stack.getItem() == Items.book && list != null && list.size() > 1)
        {
            list.remove(this.rand.zrange(list.size()));
        }

        return list;
    }

    public void onContainerClosed(EntityNPC playerIn)
    {
        super.onContainerClosed(playerIn);

        if (!this.world.client)
        {
            for (int i = 0; i < this.table.getSizeInventory(); ++i)
            {
                ItemStack itemstack = this.table.removeStackFromSlot(i);

                if (itemstack != null)
                {
                    playerIn.dropPlayerItemWithRandomChoice(itemstack, false);
                }
            }
        }
    }

    public boolean canInteractWith(EntityNPC playerIn)
    {
        return this.world.getState(this.position).getBlock() != Blocks.enchanting_table ? false : playerIn.getDistanceSq((double)this.position.getX() + 0.5D, (double)this.position.getY() + 0.5D, (double)this.position.getZ() + 0.5D) <= 64.0D;
    }

    public ItemStack transferStackInSlot(EntityNPC playerIn, int index)
    {
        ItemStack itemstack = null;
        Slot slot = (Slot)this.inventorySlots.get(index);

        if (slot != null && slot.getHasStack())
        {
            ItemStack itemstack1 = slot.getStack();
            itemstack = itemstack1.copy();

            if (index == 0)
            {
                if (!this.mergeItemStack(itemstack1, 1, 37, true))
                {
                    return null;
                }
            }
            else
            {
                if (((Slot)this.inventorySlots.get(0)).getHasStack() || !((Slot)this.inventorySlots.get(0)).isItemValid(itemstack1))
                {
                    return null;
                }

                if (itemstack1.hasTagCompound() && itemstack1.size == 1)
                {
                    ((Slot)this.inventorySlots.get(0)).putStack(itemstack1.copy());
                    itemstack1.size = 0;
                }
                else if (itemstack1.size >= 1)
                {
                    ((Slot)this.inventorySlots.get(0)).putStack(new ItemStack(itemstack1.getItem()));
                    --itemstack1.size;
                }
            }

            if (itemstack1.size == 0)
            {
                slot.putStack((ItemStack)null);
            }
            else
            {
                slot.onSlotChanged();
            }

            if (itemstack1.size == itemstack.size)
            {
                return null;
            }

            slot.onPickupFromSlot(playerIn, itemstack1);
        }

        return itemstack;
    }
}
