package common.item;

import java.lang.reflect.InvocationTargetException;
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.CharacterInfo;
import common.entity.npc.EntityNPC;
import common.entity.npc.EntityNPC.CharacterTypeData;
import common.entity.types.EntityLiving;
import common.init.EntityRegistry;
import common.init.UniverseRegistry;
import common.model.Model;
import common.model.ModelProvider;
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 ItemNpcSpawner extends Item
{
	private final CharacterInfo spawned;
	
    public ItemNpcSpawner(CharacterInfo spawned)
    {
//        this.setHasSubtypes(true);
        this.setTab(CheatTab.tabSpawners);
        this.spawned = spawned;
    }

    public String getDisplay(ItemStack stack)
    {
        String item = "Erschaffe";
        CharacterInfo info = this.spawned; // SpeciesRegistry.CHARACTERS.get(stack.getMetadata() % SpeciesRegistry.CHARACTERS.size());
        String species = EntityRegistry.getEntityName(info.species.id);
        if(info.species.prefix && info.type != null && !info.type.toString().isEmpty())
        	species = info.type.toString();
        String character = info.name;
        item = item + " " + species + (character.isEmpty() ? "" : (" " + character));

        return item;
    }

    public int getColorFromItemStack(ItemStack stack, int renderPass)
    {
        return renderPass == 0 ? this.spawned.color1 : this.spawned.color2;
    }
    
    public void addInformation(ItemStack stack, EntityNPC player, List<String> tooltip) {
    	Dimension dim = this.spawned.species.origin == null ? null : UniverseRegistry.getDimension(this.spawned.species.origin);
		tooltip.add(TextColor.ORANGE + "Herkunft: " + (dim == null ? "???" : dim.getFormattedName(false)));
    }
    
    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);

            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 = spawnNpc(worldIn, this.spawned, (double)pos.getX() + 0.5D, (double)pos.getY() + d0, (double)pos.getZ() + 0.5D);

            if (entity != null)
            {
                if (stack.hasDisplayName())
                {
                    entity.setCustomNameTag(stack.getDisplayName());
                }

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

            return true;
        }
    }
    
    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 = spawnNpc(worldIn, this.spawned, (double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.5D, (double)blockpos.getZ() + 0.5D);

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

//	                            if (!playerIn.creative)
//	                            {
                            --itemStackIn.stackSize;
//	                            }
                            
//	                            if(z == 0)
//	                            	playerIn.triggerAchievement(StatRegistry.objectUseStats[ItemRegistry.getIdFromItem(this)]);
                        }
//                        }
                    }
                }

                return itemStackIn;
            }
        }
    }
    
    public static Entity spawnNpc(World worldIn, CharacterInfo character, double x, double y, double z)
    {
//        CharacterInfo character = SpeciesRegistry.CHARACTERS.get(entityID % SpeciesRegistry.CHARACTERS.size());
        EntityNPC entity;
		try {
			entity = character.species.clazz.getConstructor(World.class).newInstance(worldIn);
		}
		catch(InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException e) {
			throw new RuntimeException(e);
		}
        entity.setLocationAndAngles(x, y, z, ExtMath.wrapf(worldIn.rand.floatv() * 360.0F), 0.0F);
        entity.headYaw = entity.rotYaw;
        entity.yawOffset = entity.rotYaw;
        entity.onInitialSpawn(new CharacterTypeData(character));
//        entity.setFromInfo(character);
        worldIn.spawnEntityInWorld(entity);
        return entity;
    }
    
//    public void getSubItems(Item itemIn, CreativeTab tab, List<ItemStack> subItems)
//    {
//        for (int z = 0; z < SpeciesRegistry.CHARACTERS.size(); z++)
//        {
//            subItems.add(new ItemStack(itemIn, 1, z));
//        }
//    }
//    
//    public ItemMeshDefinition getMesher() {
//    	return new ItemMeshDefinition()
//        {
//    		public String getModelLocation(ItemStack stack)
//            {
//                return "item/npc_spawner#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(), "npc_spawner", "npc_spawner_overlay");
    }
}
