package com.zivilon.cinder_loe.items;

import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.World;

import com.zivilon.cinder_loe.CinderLoE;

public class CinderLoESpawnEgg extends Item {
    private Class<? extends Entity> entityClass;

    public CinderLoESpawnEgg(Class<? extends Entity> entityClass) {
        this.entityClass = entityClass;
        this.setUnlocalizedName("spawn_egg_" + entityClass.getSimpleName().toLowerCase());
        this.setTextureName("spawn_egg");
        this.setCreativeTab(CreativeTabs.tabMisc); // Or any other tab you prefer
    }

    @Override
    public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player) {
        if (!world.isRemote) {
            // Perform a ray trace to find the block the player is looking at
            MovingObjectPosition target = getMovingObjectPositionFromPlayer(world, player, true);
            
            if (target != null && target.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) {
                int x = target.blockX;
                int y = target.blockY;
                int z = target.blockZ;
                
                // Adjust the y coordinate to spawn the entity on top of the block clicked
                y += 1;

                try {
                    Entity entity = entityClass.getConstructor(World.class).newInstance(world);
                    entity.setLocationAndAngles(x + 0.5, y, z + 0.5, MathHelper.wrapAngleTo180_float(world.rand.nextFloat() * 360.0F), 0.0F);
                    spawnCustomCreature(world, entity);
                } catch (Exception e) {
                    e.printStackTrace(); // Log any exceptions
                }
            }
        }
        if (!player.capabilities.isCreativeMode) {
            --itemStack.stackSize;
        }
        return itemStack;
    }


    public static void spawnCustomCreature(World world, Entity entity) {
        if (entity instanceof EntityLiving) {
            EntityLiving entityLiving = (EntityLiving)entity;
            
            // The entity's location is already set, so we directly apply custom properties and spawn
            entityLiving.onSpawnWithEgg(null); // Applies custom armor and equipment
            
            world.spawnEntityInWorld(entity);
            entityLiving.playLivingSound();
        }
    }
}
