package common.inventory;

import common.entity.Entity;
import common.entity.item.EntityItem;
import common.item.ItemStack;
import common.rng.Random;
import common.util.BlockPos;
import common.world.World;

public class InventoryHelper
{
    private static final Random RANDOM = new Random();

    public static void dropInventoryItems(World worldIn, BlockPos pos, IInventory inventory)
    {
        dropInventoryItems(worldIn, (double)pos.getX(), (double)pos.getY(), (double)pos.getZ(), inventory);
    }

    public static void dropInventoryItems(World worldIn, Entity entityAt, IInventory inventory)
    {
        dropInventoryItems(worldIn, entityAt.posX, entityAt.posY, entityAt.posZ, inventory);
    }

    private static void dropInventoryItems(World worldIn, double x, double y, double z, IInventory inventory)
    {
        for (int i = 0; i < inventory.getSizeInventory(); ++i)
        {
            ItemStack itemstack = inventory.getStackInSlot(i);

            if (itemstack != null)
            {
                spawnItemStack(worldIn, x, y, z, itemstack);
            }
        }
    }

    private static void spawnItemStack(World worldIn, double x, double y, double z, ItemStack stack) // fixed: large sizes
    {
        float f = RANDOM.floatv() * 0.8F + 0.1F;
        float f1 = RANDOM.floatv() * 0.8F + 0.1F;
        float f2 = RANDOM.floatv() * 0.8F + 0.1F;

        while (stack.size > 0)
        {
            int i = stack.size > 64 ? stack.size : (RANDOM.zrange(21) + 10);

            if (i > stack.size)
            {
                i = stack.size;
            }

            stack.size -= i;
            EntityItem entityitem = new EntityItem(worldIn, x + (double)f, y + (double)f1, z + (double)f2, new ItemStack(stack.getItem(), i));

            if (stack.hasTagCompound())
            {
                entityitem.getEntityItem().setTagCompound(stack.getTagCompound().copy());
            }

            float f3 = 0.05F;
            entityitem.motionX = RANDOM.gaussian() * (double)f3;
            entityitem.motionY = RANDOM.gaussian() * (double)f3 + 0.20000000298023224D;
            entityitem.motionZ = RANDOM.gaussian() * (double)f3;
            worldIn.spawnEntityInWorld(entityitem);
        }
    }
}
