package common.item;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import common.attributes.Attribute;
import common.attributes.AttributeModifier;
import common.collect.Maps;
import common.collect.Sets;
import common.color.TextColor;
import common.entity.npc.EntityNPC;
import common.entity.projectile.EntityPotion;
import common.init.Items;
import common.init.SoundEvent;
import common.model.ItemMeshDefinition;
import common.model.Model;
import common.model.ModelProvider;
import common.potion.Potion;
import common.potion.PotionEffect;
import common.potion.PotionHelper;
import common.world.World;

import java.util.Set;

public class ItemPotion extends Item
{
    private Map<Integer, List<PotionEffect>> effectCache = Maps.<Integer, List<PotionEffect>>newHashMap();
    private static final Map<List<PotionEffect>, Integer> SUB_ITEMS_CACHE = Maps.<List<PotionEffect>, Integer>newLinkedHashMap();

    public ItemPotion()
    {
        this.setMaxStackSize(1);
        this.setHasSubtypes(true);
        this.setMaxDamage(0);
        this.setTab(CheatTab.tabMagic);
		this.setColor(TextColor.ORK);
    }

    public List<PotionEffect> getEffects(ItemStack stack)
    {
//        if (stack.hasTagCompound() && stack.getTagCompound().hasKey("CustomPotionEffects", 9))
//        {
//            List<PotionEffect> list1 = Lists.<PotionEffect>newArrayList();
//            NBTTagList nbttaglist = stack.getTagCompound().getTagList("CustomPotionEffects", 10);
//
//            for (int i = 0; i < nbttaglist.tagCount(); ++i)
//            {
//                NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i);
//                PotionEffect potioneffect = PotionEffect.readCustomPotionEffectFromNBT(nbttagcompound);
//
//                if (potioneffect != null)
//                {
//                    list1.add(potioneffect);
//                }
//            }
//
//            return list1;
//        }
//        else
//        {
        List<PotionEffect> list = (List)this.effectCache.get(Integer.valueOf(stack.getMetadata()));

        if (list == null)
        {
            list = PotionHelper.getPotionEffects(stack.getMetadata());
            this.effectCache.put(Integer.valueOf(stack.getMetadata()), list);
        }

        return list;
//        }
    }

    public List<PotionEffect> getEffects(int meta)
    {
        List<PotionEffect> list = (List)this.effectCache.get(Integer.valueOf(meta));

        if (list == null)
        {
            list = PotionHelper.getPotionEffects(meta);
            this.effectCache.put(Integer.valueOf(meta), list);
        }

        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.stackSize;
//        }

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

            if (list != null)
            {
                for (PotionEffect potioneffect : list)
                {
                    playerIn.addEffect(new PotionEffect(potioneffect));
                }
            }
        }

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

//        if (!playerIn.creative)
//        {
        if (stack.stackSize <= 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 (isSplash(itemStackIn.getMetadata()))
        {
//            if (!playerIn.creative)
//            {
            --itemStackIn.stackSize;
//            }

            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;
        }
    }

    /**
     * returns wether or not a potion is a throwable splash potion based on damage value
     */
    public static boolean isSplash(int meta)
    {
        return (meta & 16384) != 0;
    }

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

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

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

        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 ((stack.getMetadata() & 16383) == 0)
        {
            return (isSplash(stack.getMetadata()) ? "Werfbare " : "") + "Wasserflasche";
        }
        else
        {
            String s = "";

            if (isSplash(stack.getMetadata()))
            {
                s = "Werfbarer ";
            }

            List<PotionEffect> list = Items.potion.getEffects(stack);

            if (list != null && !list.isEmpty())
            {
                String s2 = ((PotionEffect)list.get(0)).getPotionName();
//                s2 = s2 + ".postfix";
                return s + s2.trim();
            }
            else
            {
                String s1 = PotionHelper.getPotionPrefix(stack.getMetadata());
                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 ((stack.getMetadata() & 16383) != 0)
        {
            List<PotionEffect> list = Items.potion.getEffects(stack);
            Map<Attribute, Set<AttributeModifier>> multimap = Maps.newHashMap();

            if (list != null && !list.isEmpty())
            {
                for (PotionEffect potioneffect : list)
                {
                    String s1 = potioneffect.getEffectName().trim();
                    Potion potion = potioneffect.getPotion();
                    Map<Attribute, AttributeModifier> map = potion.getModifiers();

                    if (map != null && map.size() > 0)
                    {
                        for (Entry<Attribute, AttributeModifier> entry : map.entrySet())
                        {
                            AttributeModifier attributemodifier = (AttributeModifier)entry.getValue();
                            AttributeModifier attributemodifier1 = new AttributeModifier(attributemodifier.getName(), potion.getAmount(potioneffect.getAmplifier(), attributemodifier), attributemodifier.isMultiplied());
                            Set<AttributeModifier> set = multimap.get(entry.getKey());
                            if(set == null)
                            	multimap.put(entry.getKey(), set = Sets.newHashSet());
                            set.add(attributemodifier1);
//                            multimap.put((Attribute)entry.getKey(), set);
                        }
                    }

                    s1 = s1 + PotionHelper.getPotionPotency(potioneffect.getAmplifier());
//                    if (potioneffect.getAmplifier() >= 1 && potioneffect.getAmplifier() <= 9)
//                    {
//                        s1 = s1 + " " + Strs.get("potion.potency." + potioneffect.getAmplifier()).trim();
//                    }
//                    else if (potioneffect.getAmplifier() != 0)
//                    {
//                        s1 = s1 + " " + (potioneffect.getAmplifier() + 1);
//                    }

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

                    if (potion.isBadEffect())
                    {
                        tooltip.add(TextColor.RED + s1);
                    }
                    else
                    {
                        tooltip.add(TextColor.LGRAY + s1);
                    }
                }
            }
            else
            {
                String s = "Wirkungslos";
                tooltip.add(TextColor.LGRAY + s);
            }

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

                for (Entry<Attribute, Set<AttributeModifier>> entry1 : multimap.entrySet())
                {
                    for(AttributeModifier attributemodifier2 : entry1.getValue()) {
	                    double d0 = attributemodifier2.getAmount();
	                    double d1;
	
	                    if (!attributemodifier2.isMultiplied())
	                    {
	                        d1 = attributemodifier2.getAmount();
	                    }
	                    else
	                    {
	                        d1 = attributemodifier2.getAmount() * 100.0D;
	                    }
	
	                    if (d0 > 0.0D)
	                    {
	                        tooltip.add(TextColor.BLUE + String.format("+%s" + (attributemodifier2.isMultiplied() ? "%%" : "") + " %s", ItemStack.DECIMALFORMAT.format(d1), entry1.getKey().getDisplayName()));
	                    }
	                    else if (d0 < 0.0D)
	                    {
	                        d1 = d1 * -1.0D;
	                        tooltip.add(TextColor.RED + String.format("-%s" + (attributemodifier2.isMultiplied() ? "%%" : "") + " %s", ItemStack.DECIMALFORMAT.format(d1), entry1.getKey().getDisplayName()));
	                    }
                    }
                }
            }
        }
    }

    public boolean hasEffect(ItemStack stack)
    {
        List<PotionEffect> list = this.getEffects(stack);
        return list != null && !list.isEmpty();
    }

    /**
     * returns a list of items with the same ID, but different meta (eg: dye returns 16 items)
     */
    public void getSubItems(Item itemIn, CheatTab tab, List<ItemStack> subItems)
    {
        super.getSubItems(itemIn, tab, subItems);
        subItems.add(new ItemStack(itemIn, 1, 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();
            subItems.add(new ItemStack(itemIn, 1, j1));
        }
    }
    
//    public Set<String> getValidTags() {
//    	return Sets.newHashSet("CustomPotionEffects");
//    }
    
//    public boolean validateNbt(NBTTagCompound tag, boolean adv) {
//    	if(tag.hasKey("CustomPotionEffects")) {
//    		if(!adv) {
//    			return false;
//    		}
//			if(!tag.hasKey("CustomPotionEffects", 9)) {
//    			return false;
//    		}
//			NBTTagList effects = tag.getTagList("CustomPotionEffects", 10);
//			if(effects.hasNoTags()) {
//    			return false;
//    		}
//		}
//    	return true;
//    }
    
    public ItemMeshDefinition getMesher() {
    	return new ItemMeshDefinition()
        {
            public String getModelLocation(ItemStack stack)
            {
                return ItemPotion.isSplash(stack.getMetadata()) ? ("item/potion#16384" + '#' + "inventory") : ("item/potion#0" + '#' + "inventory");
            }
        };
    }
    
    public void getRenderItems(Item itemIn, List<ItemStack> subItems) {
    	subItems.add(new ItemStack(itemIn, 1, 0));
    	subItems.add(new ItemStack(itemIn, 1, 16384));
    }

    public Model getModel(ModelProvider provider, String name, int meta) {
    	return provider.getModel(this.getTransform(), "potion_overlay", 
    			isSplash(meta) ? "potion_bottle_splash" : "potion_bottle_drinkable");
    }
}
