// This script contains functionality to allow bots to take ammo or health from cabinets
this.Name = "UseCabinet";
this.Parent = "HighLevel";
this.SkipGetPriorityWhenActive = true;
this.AutoAdd = (GetModName() != "infected");

this.CAB_HEALTH = 1;
this.CAB_AMMO = 2;

this.CabinetData = {};

this.Initialize = function()
{
	//allocate query tables for this bot, they cannot be shared
	this.QueryHealth = {};
	this.QueryAmmo = {};

	// check for current health/ammo and cabinet status so we can finish if cabinet is empty or bot has enough health/ammo
	this.LimitTo(this.CheckDesire, 2, true);
};

this.CheckDesire = function()
{
	if (!this.MapGoal){ return true; }

	ent = this.MapGoal.GetEntity();
	if (ent && GetCabinetData(ent, this.CabinetData) && this.CabinetData.CurrentAmount==0){
		//cabinet is empty
		this.BlackboardDelay(20);
		return false;
	}

	switch(this.CabinetType)
	{
		case this.CAB_HEALTH:
		{
			return this.Bot.GetHealthPercent() < 1;
		}
		case this.CAB_AMMO:
		{
			return !this.Bot.HasAmmo(this.AmmoType, this.AmmoAmount);
		}
	}
};

this.GetPriority = function()
{
	ammo = Util.DesireTable;
	c = this.Bot.GetClass();
	medic = c == CLASS.MEDIC;
	fieldops = c == CLASS.FIELDOPS;
	healthPriority = 0;

	for(;;)
	{
		this.Priority = 0;

		if(!medic)
		{
			healthPriority = 1.0 - this.Bot.GetHealthPercent();
			if(healthPriority > 0.7)
			{
				if (this.QueryGoals(this.QueryHealth, 0x63217fa7 /* HEALTHCAB */))
				{
					this.DestGoals = this.QueryHealth;
					this.CabinetType = this.CAB_HEALTH;
					this.Priority = healthPriority;
				}
			}
		}
		if(!fieldops)
		{
			this.Bot.GetMostDesiredAmmo(ammo);
			ammoPriority = ammo.Desire;
			if(ammoPriority > healthPriority && ammoPriority > 0.7 && ammo.AmmoType>=0)
			{
				if (this.QueryGoals(this.QueryAmmo, 0x52ad0a47 /* AMMOCAB */))
				{
					this.DestGoals = this.QueryAmmo;
					this.CabinetType = this.CAB_AMMO;
					this.AmmoType = ammo.AmmoType;
					this.AmmoAmount = ammo.GetAmmo;
					this.Priority = ammoPriority;
				}
			}
		}
		sleep(2);
	}
};

this.Enter = function()
{
	//find the nearest cabinet
	positions = {};
	foreach(id and goal in this.DestGoals)
	{
		 positions[id] = goal.GetPosition();
	}
	id = this.Bot.GetNearestDestination(positions);
	if(IsNull(id))
	{
		//path not found, delay all available cabinets
		foreach(goal in this.DestGoals)
		{
			this.BlackboardDelay(10, goal);
		}
		this.Finished();
	}
	this.MapGoal = this.DestGoals[id];
	this.DestGoals = null;

	this.MarkInProgress();
};

this.Exit = function()
{
	this.MapGoal = null;
};

this.Update = function()
{
	Util.RouteTo(this);

	pos = this.MapGoal.GetUsePoint(-1);

	for(timeout = 300; this.CheckDesire(); --timeout)
	{
		this.Bot.MoveTowards(pos);
		yield();
		if (timeout < 0) {
			this.BlackboardDelay(30);
			Util.ScriptDebugPrint(this.MapGoal.GetName(), "timedout");
			break;
		}
	}

	this.Finished();
};
