package common.item.tool;

import common.block.Block;
import common.block.artificial.BlockFence;
import common.entity.item.EntityLeashKnot;
import common.entity.npc.EntityNPC;
import common.entity.types.EntityLiving;
import common.item.CheatTab;
import common.item.Item;
import common.item.ItemStack;
import common.util.BlockPos;
import common.util.BoundingBox;
import common.util.Facing;
import common.world.World;

public class ItemLead extends Item
{
    public ItemLead()
    {
        this.setTab(CheatTab.TOOLS);
    }

    /**
     * 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)
    {
        Block block = worldIn.getState(pos).getBlock();

        if (block instanceof BlockFence)
        {
            if (worldIn.client)
            {
                return true;
            }
            else
            {
                attachToFence(playerIn, worldIn, pos);
                return true;
            }
        }
        else
        {
            return false;
        }
    }

    public static boolean attachToFence(EntityNPC player, World worldIn, BlockPos fence)
    {
        EntityLeashKnot entityleashknot = EntityLeashKnot.getKnotForPosition(worldIn, fence);
        boolean flag = false;
        double d0 = 7.0D;
        int i = fence.getX();
        int j = fence.getY();
        int k = fence.getZ();

        for (EntityLiving entityliving : worldIn.getEntitiesWithinAABB(EntityLiving.class, new BoundingBox((double)i - d0, (double)j - d0, (double)k - d0, (double)i + d0, (double)j + d0, (double)k + d0)))
        {
            if (entityliving.getLeashed() && entityliving.getLeashedTo() == player)
            {
                if (entityleashknot == null)
                {
                    entityleashknot = EntityLeashKnot.createKnot(worldIn, fence);
                }

                entityliving.setLeashedTo(entityleashknot, true);
                flag = true;
            }
        }

        return flag;
    }
}
