// This script contains functionality to allow bots to call for health when they need it

this.Name = "AskForHealth";
this.Parent = "HighLevel";
this.SkipGetPriorityWhenActive = true;

if(!BB.PICKUPHEALTH) {
	BB.PICKUPHEALTH = Blackboard.MakeKey();
}

// These parameters are optional
this.LimitToNoClass(CLASS.MEDIC); //Medics shouldn't call for health

this.Initialize = function()
{
	if ( GetGameState() != "Playing" ) {
		this.Disable = true;
	}

	// Internal variables
	this.HealthThreshold = 50.0;
	this.RangeForPack = 1000.0;
	this.Counter = 0;
	this.Timeout = 1000; // milliseconds

	Util.ScriptDebugPrint(this.Name, "initialized");
};

this.Enter = function()
{
	bbRecord = {
		Owner = this.BlackboardId,
		Target = this.BlackboardId,
	};
	Blackboard.PostRecord(BB.PICKUPHEALTH, bbRecord);

	this.AddFinishCriteria(this.Pack, "deleted");
	this.AddFinishCriteria(this.Bot.GetGameEntity(), "health greaterthan", this.HealthThreshold);
};

this.Exit = function()
{
	this.Pack = null;
	this.ReleaseAimRequest();
};

this.GetPriority = function()
{
	while(1)
	{
		this.Counter += 1;

		if( this.Bot.Health < this.HealthThreshold && this.Bot.Health > 0 )
		{
			this.Pack = this.Bot.GetNearest( CAT.PICKUP, CLASS.HEALTH );

			botId = this.Bot.GetGameId();
			if ( !this.BlackboardIsDelayed(botId) &&this.Pack && GetEntPosition(this.Pack) && this.Bot.DistanceTo(this.Pack) <= this.RangeForPack ) {
				this.BlackboardId = botId;
				this.Priority = 0.8;
			}
			else {
				if ( (this.Counter % 3 == 0) && (Util.AliveCount(this.Bot.GetTeam(), CLASS.MEDIC) > 0) && GetGameState() == "Playing" ) {
					this.Bot.SayVoice(VOICE.NEED_MEDIC);
				}
			}
		}

		sleep(10);
	}
};

this.Update = function()
{
	if ( this.Pack ) {
		pos = GetEntPosition(this.Pack);
		if ( !pos || this.Goto(pos) == EVENT.PATH_FAILED ) {
			this.BlackboardDelay(10, this.BlackboardId);
			this.Finished();
		}

		timeout = 0;
		while ( this.Pack && timeout < this.Timeout )
		{
			pos = GetEntPosition(this.Pack);
			if ( pos ) {
				this.AddAimRequest( Priority.High, "position", pos );
				this.Bot.MoveTowards( pos );
			}
			else {
				this.BlackboardDelay(10, this.BlackboardId);
				this.Finished();
			}

			timeout += 50;
			yield();
		}
	}

	this.Finished();
};

