package common.item.tool;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import common.collect.Lists;
import common.collect.Maps;
import common.color.TextColor;
import common.entity.npc.EntityNPC;
import common.entity.projectile.EntityPotion;
import common.init.Items;
import common.init.SoundEvent;
import common.item.CheatTab;
import common.item.Item;
import common.item.ItemAction;
import common.item.ItemStack;
import common.model.Model;
import common.model.ModelProvider;
import common.potion.Potion;
import common.potion.PotionEffect;
import common.potion.PotionHelper;
import common.tileentity.TileEntity;
import common.util.BlockPos;
import common.util.Facing;
import common.util.Vec3;
import common.world.World;

public class ItemPotion extends Item
{
    private static final Map<Integer, ItemPotion> POTIONS = Maps.newTreeMap();
    private static final Map<List<PotionEffect>, Integer> SUB_ITEMS_CACHE = Maps.<List<PotionEffect>, Integer>newLinkedHashMap();
    
    private final int data;
    
    private List<PotionEffect> effectCache;
    
    public static ItemPotion getPotionItem(int data) {
    	return POTIONS.getOrDefault(data, (data & 16384) != 0 ? Items.splash_potion : Items.potion);
    }
    
    public static Collection<ItemPotion> getPotions() {
    	return POTIONS.values();
    }

    public ItemPotion(int data)
    {
    	this.data = data;
        this.setMaxAmount(1);
        this.setTab(CheatTab.MAGIC);
		this.setColor(TextColor.ORK);
		POTIONS.put(data, this);
    }
    
    public int getPotionData() {
    	return this.data;
    }

    public List<PotionEffect> getEffects()
    {
        List<PotionEffect> list = this.effectCache;

        if (list == null)
        {
            list = this.effectCache = PotionHelper.getPotionEffects(this.data);
        }

        return list;
    }

    /**
     * Called when the player finishes using this Item (E.g. finishes eating.). Not called when the player stops using
     * the Item before the action is complete.
     */
    public ItemStack onItemUseFinish(ItemStack stack, World worldIn, EntityNPC playerIn)
    {
//        if (!playerIn.creative)
//        {
        --stack.size;
//        }

        if (!worldIn.client)
        {
            List<PotionEffect> list = this.getEffects();

            if (list != null)
            {
                for (PotionEffect potioneffect : list)
                {
                	if(potioneffect.getPotion().isInstant())
                		potioneffect.getPotion().onImpact(null, null, playerIn, potioneffect.getAmplifier(), 1.0);
                	else
                		playerIn.addEffect(new PotionEffect(potioneffect));
                }
            }
        }

//        playerIn.triggerAchievement(StatRegistry.objectUseStats[ItemRegistry.getIdFromItem(this)]);

//        if (!playerIn.creative)
//        {
        if (stack.size <= 0)
        {
            return new ItemStack(Items.glass_bottle);
        }

        playerIn.inventory.addItemStackToInventory(new ItemStack(Items.glass_bottle));
//        }

        return stack;
    }

    /**
     * How long it takes to use or consume an item
     */
    public int getMaxItemUseDuration(ItemStack stack)
    {
        return 32;
    }

    /**
     * returns the action that specifies what animation to play when the items is being used
     */
    public ItemAction getItemUseAction(ItemStack stack)
    {
        return ItemAction.DRINK;
    }

    /**
     * Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer
     */
    public ItemStack onItemRightClick(ItemStack itemStackIn, World worldIn, EntityNPC playerIn)
    {
        if (this.isSplashPotion())
        {
//            if (!playerIn.creative)
//            {
            --itemStackIn.size;
//            }

            worldIn.playSoundAtEntity(playerIn, SoundEvent.THROW, 0.5F);

            if (!worldIn.client)
            {
                worldIn.spawnEntityInWorld(new EntityPotion(worldIn, playerIn, itemStackIn));
            }

//            playerIn.triggerAchievement(StatRegistry.objectUseStats[ItemRegistry.getIdFromItem(this)]);
            return itemStackIn;
        }
        else
        {
            playerIn.setItemInUse(itemStackIn, this.getMaxItemUseDuration(itemStackIn));
            return itemStackIn;
        }
    }
    
    public boolean isSplashPotion() {
    	return (this.data & 16384) != 0;
    }

    public int getColorFromDamage()
    {
        return PotionHelper.getLiquidColor(this.data);
    }

    public int getColorFromItemStack(ItemStack stack, int renderPass)
    {
        return renderPass > 0 ? 16777215 : this.getColorFromDamage();
    }

    public boolean isEffectInstant()
    {
        List<PotionEffect> list = this.getEffects();

        if (list != null && !list.isEmpty())
        {
            for (PotionEffect potioneffect : list)
            {
                if (potioneffect.getPotion().isInstant())
                {
                    return true;
                }
            }

            return false;
        }
        else
        {
            return false;
        }
    }

    public String getDisplay(ItemStack stack)
    {
        if ((this.data & 16383) == 0)
        {
            return (this.isSplashPotion() ? "Werfbare " : "") + "Wasserflasche";
        }
        else
        {
            String s = "";

            if (this.isSplashPotion())
            {
                s = "Werfbarer ";
            }

            List<PotionEffect> list = this.getEffects();

            if (list != null && !list.isEmpty())
            {
                String s2 = list.get(0).getPotionName();
//                s2 = s2 + ".postfix";
                return s + s2.trim();
            }
            else
            {
                String s1 = PotionHelper.getPotionPrefix(this.data);
                return s1.trim() + " " + super.getDisplay(stack);
            }
        }
    }

    /**
     * allows items to add custom lines of information to the mouseover description
     */
    public void addInformation(ItemStack stack, EntityNPC playerIn, List<String> tooltip)
    {
        if ((this.data & 16383) != 0)
        {
            List<PotionEffect> list = this.getEffects();
            List<String> implications = Lists.newArrayList();

            if (list != null && !list.isEmpty())
            {
                for (PotionEffect potioneffect : list)
                {
                    String s1 = potioneffect.getEffectName().trim();
                    Potion potion = potioneffect.getPotion();

                    if (potioneffect.getDuration() > 20)
                    {
                        s1 = s1 + " (" + potioneffect.getDurationString() + ")";
                    }

                    if (potion.isBadEffect())
                    {
                        tooltip.add(TextColor.RED + s1);
                    }
                    else
                    {
                        tooltip.add(TextColor.LGRAY + s1);
                    }
                    String effectTip = potioneffect.getPotion().getTooltip(potioneffect.getAmplifier());
                    if(effectTip != null)
                    	implications.add(effectTip);
                }
            }
            else
            {
                String s = "Wirkungslos";
                tooltip.add(TextColor.LGRAY + s);
            }

            if (!implications.isEmpty())
            {
                tooltip.add("");
                tooltip.add(TextColor.DMAGENTA + "Auswirkungen:");
                tooltip.addAll(implications);
            }
        }
    }

    public boolean hasEffect(ItemStack stack)
    {
        List<PotionEffect> list = this.getEffects();
        return list != null && !list.isEmpty();
    }
    
    public static String getPotionName(ItemPotion potion) { //TODO: fix potion names
    	if((potion.getPotionData() & 16383) == 0)
    		return potion.isSplashPotion() ? "splash_potion" : "potion";
    	List<PotionEffect> list = potion.getEffects();
    	if(list == null || list.isEmpty())
    		return (potion.isSplashPotion() ? "splash_potion_" : "potion_") + PotionHelper.getPotionPrefixIndex(potion.getPotionData());
    	PotionEffect effect = list.get(0);
    	return (potion.isSplashPotion() ? "splash_potion_" : "potion_") + effect.getPotion().getName() + (effect.getAmplifier() == 0 ? "" : "_" + (effect.getAmplifier() + 1)) + (effect.getPotion().isInstant() ? "" : "_" + effect.getDuration());
    }

    public static List<Integer> getValidDataValues()
    {
        List<Integer> data = Lists.newArrayList();
        data.add(0);
        data.add(16384);

        if (SUB_ITEMS_CACHE.isEmpty())
        {
            for (int i = 0; i <= 15; ++i)
            {
                for (int j = 0; j <= 1; ++j)
                {
                    int lvt_6_1_;

                    if (j == 0)
                    {
                        lvt_6_1_ = i | 8192;
                    }
                    else
                    {
                        lvt_6_1_ = i | 16384;
                    }

                    for (int l = 0; l <= 2; ++l)
                    {
                        int i1 = lvt_6_1_;

                        if (l != 0)
                        {
                            if (l == 1)
                            {
                                i1 = lvt_6_1_ | 32;
                            }
                            else if (l == 2)
                            {
                                i1 = lvt_6_1_ | 64;
                            }
                        }

                        List<PotionEffect> list = PotionHelper.getPotionEffects(i1);

                        if (list != null && !list.isEmpty())
                        {
                            SUB_ITEMS_CACHE.put(list, Integer.valueOf(i1));
                        }
                    }
                }
            }
        }

        Iterator iterator = SUB_ITEMS_CACHE.values().iterator();

        while (iterator.hasNext())
        {
            int j1 = ((Integer)iterator.next()).intValue();
            data.add(j1);
        }
        
        return data;
    }

    public Model getModel(ModelProvider provider, String name) {
    	return provider.getModel(this.getTransform(), "potion_overlay", this.isSplashPotion() ? "potion_bottle_splash" : "potion_bottle_drinkable");
    }
    
	public ItemStack dispenseStack(World world, TileEntity source, Vec3 position, BlockPos blockpos, Facing facing, ItemStack stack) {
		if(this.isSplashPotion())
			return this.dispenseProjectile(world, facing, stack, new EntityPotion(world, position.xCoord, position.yCoord, position.zCoord, stack.copy()), 1.375f, 3.0f);
		return super.dispenseStack(world, source, position, blockpos, facing, stack);
	}

	public int getDispenseSoundId() {
		return this.isSplashPotion() ? 1002 : super.getDispenseSoundId();
	}
}
