// This script contains functionality to allow bots to watch their own health and call for health when
// they are below a certain health value.

if(ScriptGoals.watch_health == null)
{
	ScriptGoals.watch_health = table();
	
	// A debug flag for enabling/disabling printed messages. Useful for debugging this goal.
	ScriptGoals.watch_health.Debug = true;
	
	// Script Goal Options
	ScriptGoals.watch_health.call_health_delay = 10.0;
	ScriptGoals.watch_health.check_health_delay = 2.0;
	
	ScriptGoals.watch_health.watchHealthFunc = function()
	{
		if( ScriptGoals.watch_health.Debug )
		{
			print("ScriptGoals.watch_health.watchHealthFunc");
		}
		
		while( true )
		{
			// What's my current health/armor.
			healthArmorTable = GetEntHealthAndArmor( this.GetGameEntity() );
		
			needsHeal = false;
			
			if( healthArmorTable.CurrentHealth <= 45 && healthArmorTable.CurrentHealth > 0 )
			{
				needsHeal = true;
			}
			
			// Only do stuff if the bot doesn't already have a script goal.
			if( needsHeal && ( this.scriptgoal == null ) )
			{
				// Check if we should self-heal
				if( this.GetClass() != CLASS.MEDIC )
				{
					this.SayVoice( VOICE.NEED_MEDIC );
					sleep( ScriptGoals.watch_health.call_health_delay );
					continue;
				}
				else
				{
					// This will take temporary control of the bot, and when done, should leave the bot
					// in the state it was initially.
					if( this.IsWeaponCharged( WEAPON.MEDKIT ) )
					{
						// Save the current settings.
						wasScriptControlled = this.IsScriptControlled();
						wasScriptControlledWeapons = this.IsScriptControlledWeapons();
						
						// Self Heal
						this.SetScriptControlled( true );
						this.SetScriptControlledWeapons( true );
						
						dowhile( this.GetCurrentWeapon() != WEAPON.MEDKIT )
						{
							this.SelectWeapon( WEAPON.MEDKIT );        
							yield();
						}
						
						endTime = GetTime() + 3500;
						dowhile( this.IsWeaponCharged( WEAPON.MEDKIT ) && ( GetTime() <= endTime ) )
						{
							this.FireWeapon();
							yield();                
						}
						
						// Set it back to the state it was before we took control.
						// This should allow existing goal scripts to continue.
						this.SetScriptControlled( wasScriptControlled );
						this.SetScriptControlledWeapons( wasScriptControlledWeapons );
					}
				}
			}
			
			sleep( ScriptGoals.watch_health.check_health_delay );
		}
	};
}

// Add the following snippet somewhere, such as a spawn callback to use this goal

// Make sure we don't have the thread already.
//if(this.WatchHealthThread == null)
//{
//	this.WatchHealthThread = this:thread(ScriptGoals.watch_health.watchHealthFunc);
//}

