package common.tileentity;

import java.util.Arrays;
import java.util.List;

import common.block.tech.BlockBrewingStand;
import common.collect.Lists;
import common.entity.npc.EntityNPC;
import common.init.Items;
import common.inventory.Container;
import common.inventory.ContainerBrewingStand;
import common.inventory.ISidedInventory;
import common.inventory.InventoryPlayer;
import common.item.Item;
import common.item.ItemStack;
import common.item.tool.ItemPotion;
import common.potion.PotionEffect;
import common.potion.PotionHelper;
import common.tags.TagObject;
import common.util.Facing;
import common.world.State;

public class TileEntityBrewingStand extends TileEntityLockable implements ITickable, ISidedInventory
{
    /** an array of the input slot indices */
    private static final int[] inputSlots = new int[] {3};

    /** an array of the output slot indices */
    private static final int[] outputSlots = new int[] {0, 1, 2};

    /** The ItemStacks currently placed in the slots of the brewing stand */
    private ItemStack[] brewingItemStacks = new ItemStack[4];
    private int brewTime;

    /**
     * an integer with each bit specifying whether that slot of the stand contains a potion
     */
    private boolean[] filledSlots;

    /**
     * used to check if the current ingredient has been removed from the brewing stand during brewing
     */
    private Item ingredientID;
    private String customName;

    /**
     * Get the name of this object. For players this returns their username
     */
    public String getName()
    {
        return this.hasCustomName() ? this.customName : "Braustand";
    }

    /**
     * Returns true if this thing is named
     */
    public boolean hasCustomName()
    {
        return this.customName != null && this.customName.length() > 0;
    }

    public void setName(String name)
    {
        this.customName = name;
    }

    /**
     * Returns the number of slots in the inventory.
     */
    public int getSizeInventory()
    {
        return this.brewingItemStacks.length;
    }

    /**
     * Like the old updateEntity(), except more generic.
     */
    public void update()
    {
        if (this.brewTime > 0)
        {
            --this.brewTime;

            if (this.brewTime == 0)
            {
                this.brewPotions();
                this.markDirty();
            }
            else if (!this.canBrew())
            {
                this.brewTime = 0;
                this.markDirty();
            }
            else if (this.ingredientID != this.brewingItemStacks[3].getItem())
            {
                this.brewTime = 0;
                this.markDirty();
            }
        }
        else if (this.canBrew())
        {
            this.brewTime = 400;
            this.ingredientID = this.brewingItemStacks[3].getItem();
        }

        if (!this.worldObj.client)
        {
            boolean[] aboolean = this.func_174902_m();

            if (!Arrays.equals(aboolean, this.filledSlots))
            {
                this.filledSlots = aboolean;
                State iblockstate = this.worldObj.getState(this.getPos());

                if (!(iblockstate.getBlock() instanceof BlockBrewingStand))
                {
                    return;
                }

                for (int i = 0; i < BlockBrewingStand.HAS_BOTTLE.length; ++i)
                {
                    iblockstate = iblockstate.withProperty(BlockBrewingStand.HAS_BOTTLE[i], Boolean.valueOf(aboolean[i]));
                }

                this.worldObj.setState(this.pos, iblockstate, 2);
            }
        }
    }

    private boolean canBrew()
    {
        if (this.brewingItemStacks[3] != null && this.brewingItemStacks[3].size > 0)
        {
            ItemStack itemstack = this.brewingItemStacks[3];

            if (!itemstack.getItem().isPotionIngredient(itemstack))
            {
                return false;
            }
            else
            {
                boolean flag = false;

                for (int i = 0; i < 3; ++i)
                {
                    if (this.brewingItemStacks[i] != null && this.brewingItemStacks[i].getItem() instanceof ItemPotion potion)
                    {
                        ItemPotion result = this.getPotionResult(potion, itemstack);

                        if (!potion.isSplashPotion() && result.isSplashPotion())
                        {
                            flag = true;
                            break;
                        }

                        List<PotionEffect> list = potion.getEffects();
                        List<PotionEffect> list1 = result.getEffects();

                        if ((potion.getPotionData() <= 0 || list != list1) && (list == null || !list.equals(list1) && list1 != null) && potion != result)
                        {
                            flag = true;
                            break;
                        }
                    }
                }

                return flag;
            }
        }
        else
        {
            return false;
        }
    }

    private void brewPotions()
    {
        if (this.canBrew())
        {
            ItemStack itemstack = this.brewingItemStacks[3];

            for (int i = 0; i < 3; ++i)
            {
                if (this.brewingItemStacks[i] != null && this.brewingItemStacks[i].getItem() instanceof ItemPotion potion)
                {
                    ItemPotion result = this.getPotionResult(potion, itemstack);
                    List<PotionEffect> list = potion.getEffects();
                    List<PotionEffect> list1 = result.getEffects();

                    if (potion.getPotionData() > 0 && list == list1 || list != null && (list.equals(list1) || list1 == null))
                    {
                        if (!potion.isSplashPotion() && result.isSplashPotion())
                        {
                            this.brewingItemStacks[i] = new ItemStack(result);
                        }
                    }
                    else if (potion != result)
                    {
                        this.brewingItemStacks[i] = new ItemStack(result);
                    }
                }
            }

            if (itemstack.getItem().hasContainerItem())
            {
                this.brewingItemStacks[3] = new ItemStack(itemstack.getItem().getContainerItem());
            }
            else
            {
                --this.brewingItemStacks[3].size;

                if (this.brewingItemStacks[3].size <= 0)
                {
                    this.brewingItemStacks[3] = null;
                }
            }
        }
    }

    private ItemPotion getPotionResult(ItemPotion potion, ItemStack stack)
    {
        return stack == null ? potion : (stack.getItem().isPotionIngredient(stack) ? ItemPotion.getPotionItem(PotionHelper.applyIngredient(potion.getPotionData(), stack.getItem().getPotionEffect(stack))) : potion);
    }

    public void readTags(TagObject compound)
    {
        super.readTags(compound);
        List<TagObject> nbttaglist = compound.getList("Items");
        this.brewingItemStacks = new ItemStack[this.getSizeInventory()];

        for (int i = 0; i < nbttaglist.size(); ++i)
        {
            TagObject nbttagcompound = nbttaglist.get(i);
            int j = nbttagcompound.getByte("Slot");

            if (j >= 0 && j < this.brewingItemStacks.length)
            {
                this.brewingItemStacks[j] = ItemStack.readFromTag(nbttagcompound);
            }
        }

        this.brewTime = compound.getShort("BrewTime");

        if (compound.hasString("CustomName"))
        {
            this.customName = compound.getString("CustomName");
        }
    }

    public void writeTags(TagObject compound)
    {
        super.writeTags(compound);
        compound.setShort("BrewTime", (short)this.brewTime);
        List<TagObject> nbttaglist = Lists.newArrayList();

        for (int i = 0; i < this.brewingItemStacks.length; ++i)
        {
            if (this.brewingItemStacks[i] != null)
            {
                TagObject nbttagcompound = new TagObject();
                nbttagcompound.setByte("Slot", (byte)i);
                this.brewingItemStacks[i].writeTags(nbttagcompound);
                nbttaglist.add(nbttagcompound);
            }
        }

        compound.setList("Items", nbttaglist);

        if (this.hasCustomName())
        {
            compound.setString("CustomName", this.customName);
        }
    }

    /**
     * Returns the stack in the given slot.
     */
    public ItemStack getStackInSlot(int index)
    {
        return index >= 0 && index < this.brewingItemStacks.length ? this.brewingItemStacks[index] : null;
    }

    /**
     * Removes up to a specified number of items from an inventory slot and returns them in a new stack.
     */
    public ItemStack decrStackSize(int index, int count)
    {
        if (index >= 0 && index < this.brewingItemStacks.length)
        {
            ItemStack itemstack = this.brewingItemStacks[index];
            this.brewingItemStacks[index] = null;
            return itemstack;
        }
        else
        {
            return null;
        }
    }

    /**
     * Removes a stack from the given slot and returns it.
     */
    public ItemStack removeStackFromSlot(int index)
    {
        if (index >= 0 && index < this.brewingItemStacks.length)
        {
            ItemStack itemstack = this.brewingItemStacks[index];
            this.brewingItemStacks[index] = null;
            return itemstack;
        }
        else
        {
            return null;
        }
    }

    /**
     * Sets the given item stack to the specified slot in the inventory (can be crafting or armor sections).
     */
    public void setInventorySlotContents(int index, ItemStack stack)
    {
        if (index >= 0 && index < this.brewingItemStacks.length)
        {
            this.brewingItemStacks[index] = stack;
        }
    }

    /**
     * Returns the maximum stack size for a inventory slot. Seems to always be 64, possibly will be extended.
     */
    public int getInventoryStackLimit()
    {
        return ItemStack.MAX_SIZE;
    }

    /**
     * Do not make give this method the name canInteractWith because it clashes with Container
     */
    public boolean isUseableByPlayer(EntityNPC player)
    {
        return this.worldObj.getTileEntity(this.pos) != this ? false : player.getDistanceSq((double)this.pos.getX() + 0.5D, (double)this.pos.getY() + 0.5D, (double)this.pos.getZ() + 0.5D) <= 64.0D;
    }

    public void openInventory(EntityNPC player)
    {
    }

    public void closeInventory(EntityNPC player)
    {
    }

    /**
     * Returns true if automation is allowed to insert the given stack (ignoring stack size) into the given slot.
     */
    public boolean isItemValidForSlot(int index, ItemStack stack)
    {
        return index == 3 ? stack.getItem().isPotionIngredient(stack) : stack.getItem() == Items.potion || stack.getItem() == Items.glass_bottle;
    }

    public boolean[] func_174902_m()
    {
        boolean[] aboolean = new boolean[3];

        for (int i = 0; i < 3; ++i)
        {
            if (this.brewingItemStacks[i] != null)
            {
                aboolean[i] = true;
            }
        }

        return aboolean;
    }

    public int[] getSlotsForFace(Facing side)
    {
        return side == Facing.UP ? inputSlots : outputSlots;
    }

    /**
     * Returns true if automation can insert the given item in the given slot from the given side. Args: slot, item,
     * side
     */
    public boolean canInsertItem(int index, ItemStack itemStackIn, Facing direction)
    {
        return this.isItemValidForSlot(index, itemStackIn);
    }

    /**
     * Returns true if automation can extract the given item in the given slot from the given side. Args: slot, item,
     * side
     */
    public boolean canExtractItem(int index, ItemStack stack, Facing direction)
    {
        return true;
    }

    public String getGuiID()
    {
        return "brewing_stand";
    }

    public Container createContainer(InventoryPlayer playerInventory, EntityNPC playerIn)
    {
        return new ContainerBrewingStand(playerInventory, this);
    }

    public int getField(int id)
    {
        switch (id)
        {
            case 0:
                return this.brewTime;

            default:
                return 0;
        }
    }

    public void setField(int id, int value)
    {
        switch (id)
        {
            case 0:
                this.brewTime = value;

            default:
        }
    }

    public int getFieldCount()
    {
        return 1;
    }

    public void clear()
    {
        for (int i = 0; i < this.brewingItemStacks.length; ++i)
        {
            this.brewingItemStacks[i] = null;
        }
    }
    
    public int getColor() {
    	return 0xffdf80;
    }
}
