package common.item;

import java.util.List;

import common.block.BlockFence;
import common.block.BlockLiquid;
import common.color.TextColor;
import common.dimension.Dimension;
import common.entity.Entity;
import common.entity.npc.EntityNPC;
import common.entity.types.EntityLiving;
import common.init.Blocks;
import common.init.EntityEggInfo;
import common.init.EntityRegistry;
import common.init.UniverseRegistry;
import common.model.Model;
import common.model.ModelProvider;
import common.tileentity.TileEntity;
import common.tileentity.TileEntityMobSpawner;
import common.util.BlockPos;
import common.util.ExtMath;
import common.util.Facing;
import common.util.HitPosition;
import common.world.State;
import common.world.World;

public class ItemMonsterPlacer extends Item
{
	private final String entityId;
	
    public ItemMonsterPlacer(String entityId)
    {
//        this.setHasSubtypes(true);
        this.setTab(CheatTab.tabSpawners);
        this.entityId = entityId;
    }
    
    public String getSpawnedId() {
    	return this.entityId;
    }

    public String getDisplay(ItemStack stack)
    {
        String s = "Erschaffe";
        String s1 = this.entityId;

        if (s1 != null)
        {
            s = s + " " + EntityRegistry.getEntityName(s1);
        }

        return s;
    }

    public int getColorFromItemStack(ItemStack stack, int renderPass)
    {
        EntityEggInfo egg = EntityRegistry.SPAWN_EGGS.get(this.entityId);
        return egg != null ? (renderPass == 0 ? egg.primaryColor : egg.secondaryColor) : 16777215;
    }
    
    public void addInformation(ItemStack stack, EntityNPC player, List<String> tooltip) {
    	EntityEggInfo egg = EntityRegistry.SPAWN_EGGS.get(this.entityId);
    	if(egg != null) {
        	Dimension dim = egg.origin == null ? null : UniverseRegistry.getDimension(egg.origin);
    		tooltip.add(TextColor.ORANGE + "Herkunft: " + (dim == null ? "???" : dim.getFormattedName(false)));
    	}
    }

    /**
     * Called when a Block is right-clicked with this Item
     */
    public boolean onItemUse(ItemStack stack, EntityNPC playerIn, World worldIn, BlockPos pos, Facing side, float hitX, float hitY, float hitZ)
    {
        if (worldIn.client)
        {
            return true;
        }
        else if (!playerIn.canPlayerEdit(pos.offset(side), side, stack))
        {
            return false;
        }
        else
        {
            State iblockstate = worldIn.getState(pos);

            if (iblockstate.getBlock() == Blocks.mob_spawner)
            {
                TileEntity tileentity = worldIn.getTileEntity(pos);

                if (tileentity instanceof TileEntityMobSpawner)
                {
//                    MobSpawnerBaseLogic mobspawnerbaselogic = ((TileEntityMobSpawner)tileentity).getSpawnerBaseLogic();
                    ((TileEntityMobSpawner)tileentity).setEntityName(this.entityId);
                    tileentity.markDirty();
                    worldIn.markBlockForUpdate(pos);

//                    if (!playerIn.creative)
//                    {
                    --stack.stackSize;
//                    }

                    return true;
                }
            }

            pos = pos.offset(side);
            double d0 = 0.0D;

            if (side == Facing.UP && iblockstate.getBlock() instanceof BlockFence)
            {
                d0 = 0.5D;
            }

            
//            int amount = Math.min(stack.stackSize, 128);
//            for(int z = 0; z < amount; z++) {
            Entity entity = spawnCreature(worldIn, this.entityId, (double)pos.getX() + 0.5D, (double)pos.getY() + d0, (double)pos.getZ() + 0.5D);

            if (entity != null)
            {
//                if (entity instanceof EntityLiving)
//                {
//                    ((EntityLiving)entity).disableDespawn();
//                }
                
                if (entity instanceof EntityLiving && stack.hasDisplayName())
                {
                    entity.setCustomNameTag(stack.getDisplayName());
                }

//	                if (!playerIn.creative)
//	                {
                --stack.stackSize;
//	                }
            }
//            }

            return true;
        }
    }

    /**
     * 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 (worldIn.client)
        {
            return itemStackIn;
        }
        else
        {
            HitPosition movingobjectposition = this.getMovingObjectPositionFromPlayer(worldIn, playerIn, true);

            if (movingobjectposition == null)
            {
                return itemStackIn;
            }
            else
            {
                if (movingobjectposition.type == HitPosition.ObjectType.BLOCK)
                {
                    BlockPos blockpos = movingobjectposition.block;

                    if (!World.isValidXZ(blockpos))
                    {
                        return itemStackIn;
                    }

                    if (!playerIn.canPlayerEdit(blockpos, movingobjectposition.side, itemStackIn))
                    {
                        return itemStackIn;
                    }

                    if (worldIn.getState(blockpos).getBlock() instanceof BlockLiquid)
                    {
//                        int amount = Math.min(itemStackIn.stackSize, 128);
//                        for(int z = 0; z < amount; z++) {
                        Entity entity = spawnCreature(worldIn, this.entityId, (double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.5D, (double)blockpos.getZ() + 0.5D);

                        if (entity != null)
                        {
//                            if (entity instanceof EntityLiving)
//                            {
//                                ((EntityLiving)entity).disableDespawn();
//                            }
                            
                            if (entity instanceof EntityLiving && itemStackIn.hasDisplayName())
                            {
                                ((EntityLiving)entity).setCustomNameTag(itemStackIn.getDisplayName());
                            }

//	                            if (!playerIn.creative)
//	                            {
                            --itemStackIn.stackSize;
//	                            }

//	                            if(z == 0)
//	                            	playerIn.triggerAchievement(StatRegistry.objectUseStats[ItemRegistry.getIdFromItem(this)]);
                        }
//                        }
                    }
                }

                return itemStackIn;
            }
        }
    }

    /**
     * Spawns the creature specified by the egg's type in the location specified by the last three parameters.
     * Parameters: world, entityID, x, y, z.
     */
    public static Entity spawnCreature(World worldIn, String entityID, double x, double y, double z)
    {
        if (!EntityRegistry.SPAWN_EGGS.containsKey(entityID))
        {
            return null;
        }
        else
        {
            Entity entity = null;

            for (int i = 0; i < 1; ++i)
            {
                entity = EntityRegistry.createEntityByName(entityID, worldIn);

                if (entity instanceof EntityLiving)
                {
                    EntityLiving entityliving = (EntityLiving)entity;
                    entity.setLocationAndAngles(x, y, z, ExtMath.wrapf(worldIn.rand.floatv() * 360.0F), 0.0F);
                    entityliving.headYaw = entityliving.rotYaw;
                    entityliving.yawOffset = entityliving.rotYaw;
                    entityliving.onInitialSpawn(null);
                    worldIn.spawnEntityInWorld(entity);
                    entityliving.playLivingSound();
                }
            }

            return entity;
        }
    }

//    /**
//     * returns a list of items with the same ID, but different meta (eg: dye returns 16 items)
//     */
//    public void getSubItems(Item itemIn, CreativeTab tab, List<ItemStack> subItems)
//    {
//        for (EntityEggInfo entitylist$entityegginfo : EntityRegistry.SPAWN_EGGS.values())
//        {
//            subItems.add(new ItemStack(itemIn, 1, entitylist$entityegginfo.spawnedID));
//        }
//    }
    
//    public ItemMeshDefinition getMesher() {
//    	return new ItemMeshDefinition()
//        {
//    		public String getModelLocation(ItemStack stack)
//            {
//                return "item/spawn_egg#0" + '#' + "inventory";
//            }
//        };
//    }
    
//    public void getRenderItems(Item itemIn, List<ItemStack> subItems) {
//    	subItems.add(new ItemStack(itemIn, 1, 0));
//    }

    public Model getModel(ModelProvider provider, String name, int meta) {
    	return provider.getModel(this.getTransform(), "spawn_egg", "spawn_egg_overlay");
    }
}
