package common.inventory;

import java.util.Iterator;
import java.util.Map;

import common.block.tech.BlockAnvil;
import common.enchantment.Enchantment;
import common.enchantment.EnchantmentHelper;
import common.entity.npc.EntityNPC;
import common.init.Blocks;
import common.init.Items;
import common.item.ItemStack;
import common.util.BlockPos;
import common.vars.Vars;
import common.world.State;
import common.world.World;

public class ContainerRepair extends Container
{
    /** Here comes out item you merged and/or renamed. */
    private IInventory outputSlot;

    /**
     * The 2slots where you put your items in that you want to merge and/or rename.
     */
    private IInventory inputSlots;
    private World theWorld;
    private BlockPos selfPosition;

    /** The maximum cost of repairing/renaming in the anvil. */
    public int maximumCost;

    /** determined by damage of input item and stackSize of repair materials */
    private int materialCost;
//    private String repairedItemName;

    /** The player that has this container open. */
    private final EntityNPC thePlayer;

    public ContainerRepair(InventoryPlayer playerInventory, World worldIn, EntityNPC player)
    {
        this(playerInventory, worldIn, BlockPos.ORIGIN, player);
    }

    public ContainerRepair(InventoryPlayer playerInventory, final World worldIn, final BlockPos blockPosIn, EntityNPC player)
    {
        this.outputSlot = new InventoryCraftResult();
        this.inputSlots = new InventoryBasic("Repair", true, 2)
        {
            public void markDirty()
            {
                super.markDirty();
                ContainerRepair.this.onCraftMatrixChanged(this);
            }
        };
        this.selfPosition = blockPosIn;
        this.theWorld = worldIn;
        this.thePlayer = player;
        this.addSlotToContainer(new Slot(this.inputSlots, 0, 27, 47));
        this.addSlotToContainer(new Slot(this.inputSlots, 1, 76, 47));
        this.addSlotToContainer(new Slot(this.outputSlot, 2, 134, 47)
        {
            public boolean isItemValid(ItemStack stack)
            {
                return false;
            }
            public boolean canTakeStack(EntityNPC playerIn)
            {
                return /* (playerIn.creative || */ playerIn.getManaPoints() >= ContainerRepair.this.maximumCost /* ) */ && ContainerRepair.this.maximumCost > 0 && this.getHasStack();
            }
            public void onPickupFromSlot(EntityNPC playerIn, ItemStack stack)
            {
//                if (!playerIn.creative)
//                {
            	if(!playerIn.worldObj.client)
            		playerIn.useMana(ContainerRepair.this.maximumCost);
//                }

                ContainerRepair.this.inputSlots.setInventorySlotContents(0, (ItemStack)null);

                if (ContainerRepair.this.materialCost > 0)
                {
                    ItemStack itemstack = ContainerRepair.this.inputSlots.getStackInSlot(1);

                    if (itemstack != null && itemstack.size > ContainerRepair.this.materialCost)
                    {
                        itemstack.size -= ContainerRepair.this.materialCost;
                        ContainerRepair.this.inputSlots.setInventorySlotContents(1, itemstack);
                    }
                    else
                    {
                        ContainerRepair.this.inputSlots.setInventorySlotContents(1, (ItemStack)null);
                    }
                }
                else
                {
                    ContainerRepair.this.inputSlots.setInventorySlotContents(1, (ItemStack)null);
                }

                ContainerRepair.this.maximumCost = 0;
                State iblockstate = worldIn.getState(blockPosIn);

                if (/* !playerIn.creative && */ !worldIn.client && Vars.anvilRepairDecay && iblockstate.getBlock() instanceof BlockAnvil anvil && playerIn.getRNG().floatv() < 0.12F)
                {
                    int l = anvil.getAnvilDamage();
                    ++l;

                    if (l >= BlockAnvil.ANVILS.length)
                    {
                        worldIn.setBlockToAir(blockPosIn);
                        worldIn.playAuxSFX(1020, blockPosIn, 0);
                    }
                    else
                    {
                        worldIn.setState(blockPosIn, BlockAnvil.getByDamage(l).getState().withProperty(BlockAnvil.FACING, iblockstate.getValue(BlockAnvil.FACING)), 2);
                        worldIn.playAuxSFX(1021, blockPosIn, 0);
                    }
                }
                else if (!worldIn.client)
                {
                    worldIn.playAuxSFX(1021, blockPosIn, 0);
                }
            }
        });

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

        for (int k = 0; k < 9; ++k)
        {
            this.addSlotToContainer(new Slot(playerInventory, k, 8 + k * 18, 142));
        }
    }

    /**
     * Callback for when the crafting matrix is changed.
     */
    public void onCraftMatrixChanged(IInventory inventoryIn)
    {
        super.onCraftMatrixChanged(inventoryIn);

        if (inventoryIn == this.inputSlots)
        {
            this.updateRepairOutput();
        }
    }

    /**
     * called when the Anvil Input Slot changes, calculates the new result and puts it in the output slot
     */
    public void updateRepairOutput()
    {
//        int i = 0;
//        int j = 1;
//        int k = 1;
//        int l = 1;
//        int i1 = 2;
//        int j1 = 1;
//        int k1 = 1;
        ItemStack stack = this.inputSlots.getStackInSlot(0);
        this.maximumCost = 1;
        int totalCost = 0;
        int repairCost = 0;
        int renameCost = 0;

        if (stack == null)
        {
            this.outputSlot.setInventorySlotContents(0, (ItemStack)null);
            this.maximumCost = 0;
        }
        else
        {
            ItemStack newStack = stack.copy();
            ItemStack repStack = this.inputSlots.getStackInSlot(1);
            Map<Enchantment, Integer> newEnch = EnchantmentHelper.getEnchantments(newStack);
            boolean isBook = false;
            repairCost = repairCost + stack.getRepairCost() + (repStack == null ? 0 : repStack.getRepairCost());
            this.materialCost = 0;

            if (repStack != null)
            {
                isBook = repStack.getItem() == Items.enchanted_book && Items.enchanted_book.getEnchantments(repStack).size() > 0;

                if (newStack.isItemStackDamageable() && newStack.getItem().getIsRepairable(stack, repStack))
                {
                    int damage = Math.min(newStack.getItemDamage(), newStack.getMaxDamage() / 4);

                    if (damage <= 0)
                    {
                        this.outputSlot.setInventorySlotContents(0, (ItemStack)null);
                        this.maximumCost = 0;
                        return;
                    }

                    int cost;

                    for (cost = 0; damage > 0 && cost < repStack.size; ++cost)
                    {
                        int j5 = newStack.getItemDamage() - damage;
                        newStack.setItemDamage(j5);
                        ++totalCost;
                        damage = Math.min(newStack.getItemDamage(), newStack.getMaxDamage() / 4);
                    }

                    this.materialCost = cost;
                }
                else
                {
                    if (!isBook && (newStack.getItem() != repStack.getItem() || !newStack.isItemStackDamageable()))
                    {
                        this.outputSlot.setInventorySlotContents(0, (ItemStack)null);
                        this.maximumCost = 0;
                        return;
                    }

                    if (newStack.isItemStackDamageable() && !isBook)
                    {
                        int mainDmg = stack.getMaxDamage() - stack.getItemDamage();
                        int repDmg = repStack.getMaxDamage() - repStack.getItemDamage();
                        int repair = repDmg + newStack.getMaxDamage() * 12 / 100;
                        int newDmg = mainDmg + repair;
                        int damage = newStack.getMaxDamage() - newDmg;

                        if (damage < 0)
                        {
                            damage = 0;
                        }

                        if (damage < newStack.getItemDamage())
                        {
                            newStack.setItemDamage(damage);
                            totalCost += 2;
                        }
                    }

                    Map<Enchantment, Integer> ench = EnchantmentHelper.getEnchantments(repStack);
                    Iterator<Enchantment> enchs = ench.keySet().iterator();

                    while (enchs.hasNext())
                    {
                        Enchantment enchantment = enchs.next();

                        if (enchantment != null)
                        {
                            int newLevel = newEnch.containsKey(enchantment) ? newEnch.get(enchantment) : 0;
                            int level = ench.get(enchantment);
                            int diff;

                            if (newLevel == level)
                            {
                                ++level;
                                diff = level;
                            }
                            else
                            {
                                diff = Math.max(level, newLevel);
                            }

                            level = diff;
                            boolean applies = enchantment.canApply(stack);

                            if (/* this.thePlayer.creative || */ stack.getItem() == Items.enchanted_book)
                            {
                                applies = true;
                            }

                            Iterator<Enchantment> newEnchs = newEnch.keySet().iterator();

                            while (newEnchs.hasNext())
                            {
                            	Enchantment nEid = newEnchs.next();

                                if (nEid != enchantment && !enchantment.canApplyTogether(nEid))
                                {
                                    applies = false;
                                    ++totalCost;
                                }
                            }

                            if (applies)
                            {
                                if (level > enchantment.getMaxLevel())
                                {
                                    level = enchantment.getMaxLevel();
                                }

                                newEnch.put(enchantment, level);
                                int cost = 0;

                                switch (enchantment.getWeight())
                                {
                                    case 1:
                                        cost = 8;
                                        break;

                                    case 2:
                                        cost = 4;

                                    case 3:
                                    case 4:
                                    case 6:
                                    case 7:
                                    case 8:
                                    case 9:
                                    default:
                                        break;

                                    case 5:
                                        cost = 2;
                                        break;

                                    case 10:
                                        cost = 1;
                                }

                                if (isBook)
                                {
                                    cost = Math.max(1, cost / 2);
                                }

                                totalCost += cost * level;
                            }
                        }
                    }
                }
            }

//            if (isBlank(this.repairedItemName))
//            {
//                if (stack.hasDisplayName())
//                {
//                    renameCost = 1;
//                    totalCost += renameCost;
//                    newStack.clearCustomName();
//                }
//            }
//            else if (!this.repairedItemName.equals(stack.getDisplayName()))
//            {
//                renameCost = 1;
//                totalCost += renameCost;
//                newStack.setStackDisplayName(this.repairedItemName);
//            }

            this.maximumCost = repairCost + totalCost;

            if (totalCost <= 0)
            {
                newStack = null;
            }

            if (renameCost == totalCost && renameCost > 0 && this.maximumCost >= 40)
            {
                this.maximumCost = 39;
            }

            if (/* Config.repairExperience && */ this.maximumCost >= 40) // && !this.thePlayer.creative)
            {
                newStack = null;
            }

            if (newStack != null)
            {
            	if(!this.theWorld.client && Vars.repairXP) {
	                int cost = newStack.getRepairCost();
	
	                if (repStack != null && cost < repStack.getRepairCost())
	                {
	                    cost = repStack.getRepairCost();
	                }
	
	                cost = cost * 2 + 1;
	                newStack.setRepairCost(cost);
            	}
                EnchantmentHelper.setEnchantments(newEnch, newStack);
            }

            this.outputSlot.setInventorySlotContents(0, newStack);
            this.detectAndSendChanges();
        }
    }

    public void onCraftGuiOpened(ICrafting listener)
    {
        super.onCraftGuiOpened(listener);
        listener.sendProgressBarUpdate(this, 0, this.maximumCost);
    }

    public void updateProgressBar(int id, int data)
    {
        if (id == 0)
        {
            this.maximumCost = data;
        }
    }

    /**
     * Called when the container is closed.
     */
    public void onContainerClosed(EntityNPC playerIn)
    {
        super.onContainerClosed(playerIn);

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

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

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

    /**
     * Take a stack from the specified inventory slot.
     */
    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 == 2)
            {
                if (!this.mergeItemStack(itemstack1, 3, 39, true))
                {
                    return null;
                }

                slot.onSlotChange(itemstack1, itemstack);
            }
            else if (index != 0 && index != 1)
            {
                if (index >= 3 && index < 39 && !this.mergeItemStack(itemstack1, 0, 2, false))
                {
                    return null;
                }
            }
            else if (!this.mergeItemStack(itemstack1, 3, 39, false))
            {
                return null;
            }

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

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

            slot.onPickupFromSlot(playerIn, itemstack1);
        }

        return itemstack;
    }

    /**
     * used by the Anvil GUI to update the Item Name being typed by the player
     */
//    public void updateItemName(String newName)
//    {
//        this.repairedItemName = newName;
//
//        if (this.getSlot(2).getHasStack())
//        {
//            ItemStack itemstack = this.getSlot(2).getStack();
//
//            if (isBlank(newName))
//            {
//                itemstack.clearCustomName();
//            }
//            else
//            {
//                itemstack.setStackDisplayName(this.repairedItemName);
//            }
//        }
//
//        this.updateRepairOutput();
//    }

//	private static boolean isBlank(String s) {
//		if(s != null && !s.isEmpty()) {
//			for(int i = 0; i < s.length(); ++i) {
//				if(!Character.isWhitespace(s.charAt(i))) {
//					return false;
//				}
//			}
//			return true;
//		}
//		else {
//			return true;
//		}
//	}
}
