package common.ai;

import common.entity.types.EntityLiving;
import common.pathfinding.PathNavigateGround;
import common.util.BlockPos;
import common.village.Village;
import common.village.VillageDoorInfo;
import common.world.AWorldServer;

public class EntityAIRestrictOpenDoor extends EntityAIBase
{
    private EntityLiving entityObj;
    private VillageDoorInfo frontDoor;

    public EntityAIRestrictOpenDoor(EntityLiving creatureIn)
    {
        this.entityObj = creatureIn;

        if (!(creatureIn.getNavigator() instanceof PathNavigateGround))
        {
            throw new IllegalArgumentException("Unsupported mob type for RestrictOpenDoorGoal");
        }
    }

    /**
     * Returns whether the EntityAIBase should begin execution.
     */
    public boolean shouldExecute()
    {
        if (((AWorldServer)this.entityObj.worldObj).isDaytime())
        {
            return false;
        }
        else
        {
            BlockPos blockpos = new BlockPos(this.entityObj);
            Village village = ((AWorldServer)this.entityObj.worldObj).getNearestVillage(blockpos, 16);

            if (village == null)
            {
                return false;
            }
            else
            {
                this.frontDoor = village.getNearestDoor(blockpos);
                return this.frontDoor == null ? false : (double)this.frontDoor.getDistanceToInsideBlockSq(blockpos) < 2.25D;
            }
        }
    }

    /**
     * Returns whether an in-progress EntityAIBase should continue executing
     */
    public boolean continueExecuting()
    {
        return ((AWorldServer)this.entityObj.worldObj).isDaytime() ? false : !this.frontDoor.getIsDetachedFromVillageFlag() && this.frontDoor.isIndoorSide(new BlockPos(this.entityObj));
    }

    /**
     * Execute a one shot task or start executing a continuous task
     */
    public void startExecuting()
    {
        ((PathNavigateGround)this.entityObj.getNavigator()).setBreakDoors(false);
        ((PathNavigateGround)this.entityObj.getNavigator()).setEnterDoors(false);
    }

    /**
     * Resets the task
     */
    public void resetTask()
    {
        ((PathNavigateGround)this.entityObj.getNavigator()).setBreakDoors(true);
        ((PathNavigateGround)this.entityObj.getNavigator()).setEnterDoors(true);
        this.frontDoor = null;
    }

    /**
     * Updates the task
     */
    public void updateTask()
    {
        this.frontDoor.incrementDoorOpeningRestrictionCounter();
    }
}
