package common.ai;

import java.util.List;

import common.entity.npc.EntityNPC;
import common.entity.types.EntityLiving;
import common.util.Vec3;

public class EntityAIPlay extends EntityAIBase {
	private EntityNPC entity;
	private EntityLiving target;
	private double speed;
	private int time;

	public EntityAIPlay(EntityNPC entity, double speed) {
		this.entity = entity;
		this.speed = speed;
		this.setMutexBits(1);
	}

	public boolean shouldExecute() {
		if(!this.entity.canPlay() || this.entity.getRNG().zrange(400) != 0)
			return false;
		List<EntityNPC> list = this.entity.worldObj.<EntityNPC>getEntitiesWithinAABB(EntityNPC.class,
				this.entity.getEntityBoundingBox().expand(6.0D, 3.0D, 6.0D));
		double d0 = Double.MAX_VALUE;
		for(EntityNPC npc : list) {
			if(npc != this.entity && !npc.isPlaying() && npc.canPlay() && !this.entity.canAttack(npc) && !npc.canAttack(this.entity)) {
				double d1 = npc.getDistanceSqToEntity(this.entity);
				if(d1 <= d0) {
					d0 = d1;
					this.target = npc;
				}
			}
		}
		if(this.target == null) {
			Vec3 vec = RandomPositionGenerator.findRandomTarget(this.entity, 16, 3);
			if(vec == null)
				return false;
		}
		return true;
	}

	public boolean continueExecuting() {
		return this.time > 0;
	}

	public void startExecuting() {
		if(this.target != null)
			this.entity.setPlaying(true);
		this.time = 1000;
	}

	public void resetTask() {
		this.entity.setPlaying(false);
		this.target = null;
	}

	public void updateTask() {
		--this.time;
		if(this.target != null) {
			if(this.entity.getDistanceSqToEntity(this.target) > 4.0D)
				this.entity.getNavigator().tryMoveToEntityLiving(this.target, this.speed);
		}
		else if(this.entity.getNavigator().noPath()) {
			Vec3 vec = RandomPositionGenerator.findRandomTarget(this.entity, 16, 3);
			if(vec == null)
				return;
			this.entity.getNavigator().tryMoveToXYZ(vec.xCoord, vec.yCoord, vec.zCoord, this.speed);
		}
	}
}
