package common.ai;

import common.entity.Entity;
import common.entity.npc.EntityNPC;
import common.world.World;
import common.world.AWorldServer;

public class EntityAINpcMate extends EntityAIBase
{
    private EntityNPC npc;
    private EntityNPC mate;
    private World worldObj;
    private int matingTimeout;

    public EntityAINpcMate(EntityNPC npc)
    {
        this.npc = npc;
        this.worldObj = npc.worldObj;
        this.setMutexBits(3);
    }
    
    public boolean shouldExecute()
    {
        if (this.npc.getGrowingAge() != 0)
        {
            return false;
        }
        else if (this.npc.getRNG().zrange(100) != 0)
        {
            return false;
        }
        else
        {
            if (this.npc.getIsWillingToMate(true))
            {
                Entity entity = ((AWorldServer)this.worldObj).findNearestEntityWithinAABB(EntityNPC.class, this.npc.getEntityBoundingBox().expand(8.0D, 3.0D, 8.0D), this.npc);

                if (entity == null)
                {
                    return false;
                }
                else
                {
                    this.mate = (EntityNPC)entity;
                    return this.mate.getGrowingAge() == 0 && this.mate.getIsWillingToMate(true);
                }
            }
            else
            {
                return false;
            }
        }
    }
    
    public void startExecuting()
    {
        this.matingTimeout = 250;
        this.npc.setMating(true);
    }
    
    public void resetTask()
    {
        this.mate = null;
        this.npc.setMating(false);
    }
    
    public boolean continueExecuting()
    {
        return this.matingTimeout >= 0 && this.npc.getGrowingAge() == 0 && this.npc.getIsWillingToMate(false);
    }
    
    public void updateTask()
    {
        --this.matingTimeout;
        this.npc.getLookHelper().setLookPositionWithEntity(this.mate, 10.0F, 30.0F);

        if (this.npc.getDistanceSqToEntity(this.mate) > 2.25D)
        {
            this.npc.getNavigator().tryMoveToEntityLiving(this.mate, 0.25D);
        }
        else if (this.matingTimeout >= 6)
        {
        	this.matingTimeout -= 5;
        }
        else if (this.matingTimeout == 0 && this.mate.isMating())
        {
            this.giveBirth();
        }

//        if (this.npc.getRNG().nextInt(35) == 0)
//        {
//            this.worldObj.setEntityState(this.npc, (byte)12);
//        }
    }

    private void giveBirth()
    {
        EntityNPC entity = this.npc.createChild(this.mate);
        this.mate.setGrowingAge(100);
        this.npc.setGrowingAge(100);
        this.mate.setIsWillingToMate(false);
        this.npc.setIsWillingToMate(false);
        entity.setGrowingAge(-24000);
        entity.setLocationAndAngles(this.npc.posX, this.npc.posY, this.npc.posZ, 0.0F, 0.0F);
        this.worldObj.spawnEntityInWorld(entity);
        this.worldObj.setEntityState(entity, (byte)12);
    }
}
