
class ZHoloduke : Actor
{
	int playerowner;
	int clock;
	bool retrieve;
	bool empty;

	void A_BeginHoloduke()
	{
		if(master) {
			playerowner = Playerpawn(master).PlayerNumber();
		}
	}

	void A_HoloDistract()
	{
		BlockThingsIterator it = BlockThingsIterator.Create(self, 1000);
		Actor monster;
		while (it.Next())
		{
			monster = it.thing;
			if (monster && monster.bISMONSTER && !monster.bFRIENDLY && monster!=self && monster.target && !monster.target.bISMONSTER)
			{
				double distance = self.distance3DSquared(monster);
				if(distance<1000*1000) monster.target = self;
			}
		}
	}

	override void OnDestroy()
	{
		if (playeringame[playerowner] && players[playerowner].mo) {
			self.A_SpawnItemEX("DukeTeleportFog");
			players[playerowner].mo.A_TakeInventory("HolodukeActive", 1);
			players[playerowner].mo.A_SetInventory("HolodukeRetrieve", 0);

			if(!retrieve && empty) {
				players[playerowner].mo.A_SetInventory("HolodukeDuration", 0);
				players[playerowner].mo.A_SetInventory("Hologram_of_Duke", 0);
			}
		}

		super.OnDestroy();
	}

	override void Tick()
	{
        	Super.Tick();

		if (playeringame[playerowner] && players[playerowner].mo) {
			if(!retrieve && !empty && self.health>0) {
				if(clock==0) {
					let inv = players[playerowner].mo.FindInventory("Hologram_of_Duke");
					if (inv!=null && inv.Amount>0) {
						players[playerowner].mo.A_TakeInventory("Hologram_of_Duke", 1);
						inv = players[playerowner].mo.FindInventory("Hologram_of_Duke");
						if (inv!=null) players[playerowner].mo.A_SetInventory("HolodukeDuration", inv.Amount); else players[playerowner].mo.A_SetInventory("HolodukeDuration", 0);
					} else if (inv==null || (inv!=null && inv.Amount<=0)) {
						empty = true;
						Destroy();
					}
				}
				clock++;
				if(clock==15) clock=0;

				let invr = players[playerowner].mo.FindInventory("HolodukeRetrieve");
				if (invr!=null && invr.Amount>0) {
					retrieve = true;
					Destroy();
				}
			}
		} else {
			Destroy();
		}
	}
}