// Trap Handler.
// Worthless Bums 2012.


// Spawns traps on the current level!
function spawnTraps ()
{//echo("spawnTraps()");
	if ($generateTutorialLevel	||
		$dungeonLevel <= 1)		// Don't spawn traps on the first level of decks!
	{
		return;
	}
	if ($overworldLocation $= "Alien Deck")
	{
		return;
	}
	
	%numberOfTraps = $TrapMaxPerLevel;
	
	// Use an offset to bound the trap spawn positions.
	%offset = 4;
	
	// Sanity check - the offset cannot be larger than the maze dimension!
	if (%offset > $mazeDimension)
	{
		// Problem - get out!
		return false;
	}
	
	// Create a space inside which monsters cannot spawn!
	%safeZone = getSafeZone();
	%minX = getWord(%safeZone, 0);
	%maxX = getWord(%safeZone, 1);
	%minY = getWord(%safeZone, 2);
	%maxY = getWord(%safeZone, 3);
	
	// Spawn the monsters!
	for (%i = 0; %i < %numberOfTraps; %i++)
	{//echo("%i =" SPC %i);
		// Make sure we spawn on a passable tile!
		// Lock the number of random placement attempts to avoid an infinite loop.
		%attempts = 0;
		%spawnTrap = false;
		do {
			%attempts++;
			// Generate a random position within specified bounds.
			%randomX = getRandom(%offset, $mazeDimension - 1 - %offset);
			%randomY = getRandom(%offset, $mazeDimension - 1 - %offset);
			
			// Make sure the tile is not in the safe zone!
			if ((%randomX < %minX	||	%randomX > %maxX)	&&
				(%randomY < %minY	||	%randomY > %maxY))
			{
				// Make sure the tile is clear!
				if (!isObject($mazeRoom[%randomX, %randomY])	&&
					!isSpaceTile(%randomX, %randomY)			&&
					tileClearOfSquadMembers(%randomX, %randomY)	&&
					tileClearOfMonsters(%randomX, %randomY)		&&
					tileClearOfTreasure(%randomX, %randomY)		&&
					tileClearOfTraps(%randomX, %randomY)		&&
					tileIsClearOfUnits(%randomX, %randomY))
				{
					%spawnTrap = true;
					break;
				}
			}
		} while (($mazeRoom[%randomX, %randomY].status == 0 || $mazeRoom[%randomX, %randomY].status == -1 || $mazeRoom[%randomX, %randomY].status == -2)	&&		// Tile status 1 is walkable, 0 is not walkable. NOTE: This is potentially an infinite loop if the maze room is filled with unwalkable tiles!
				 %attempts < 20)
		
		// Check if a trap was spawned.
		if (%spawnTrap)
		{
			// Spawn random trap!
			%trap = spawnRandomTrap(%randomX, %randomY);
			
			// Save the newly spawned trap.
			$trapList.add(%trap);
		}
	}
}

// Checks if a character is on a trap.
function characterOnTrap (%character)
{//echo("characterOnTrap()");
	// Loop through map items to see if character is on a trap.
	for (%i = 0; %i < $trapList.getCount(); %i++)
	{
		// Grab trap.
		%trap = $trapList.getObject(%i);
		
		if (%character.xIndex == %trap.xIndex	&&
			%character.yIndex == %trap.yIndex)
		{
			// Add any trap animation/sound effects here!
			// Nothing here yet!
			
			// Delete trap.
			%trap.setVisible(false);
			%trap.safeDelete();
			
			// Use the character's Demolitions skill to avoid trap damage!
			if (getRandom(1, 100) < %character.demolitions * 25)
			{
				// Play sound effect.
				playAudio("Audio:diffuseTrap", EffectsAudioVolume.value);
				// Update event log.
				updateEventText($squadColor @ %character.name @ $whiteColor @ " deactivates " @ $friendlyActionColor @ %trap.name @ $defaultColor @ "!");
				
				return;
			}
			
			// Deal environmental damage to the character!
			//dealEnvironmentalDamage(%character, %trap.trapDamage, true);
			// HACK: Schedule so onPositionTarget() doesn't crash!
			schedule(150, 0, "dealEnvironmentalDamage", %character, %trap.trapDamage, true);
			// END OF HACK
			
			
			// Update event log.
			updateEventText($squadColor @ %character.name @ $whiteColor @ " takes " @ $damageColor @ %trap.trapDamage @ " damage " @ $friendlyActionColor @ "from " @ %trap.name @ $defaultColor @ "!");
			
			// Traps have a chance to permanently reduce gear stats!
			%trapReductionRoll = getRandom(1, 100);
			if (%trapReductionRoll <= $trapReductionChance)
			{
				// Determine what gear stat to reduce.
				%gearStatRoll = getRandom(0, 4);
				switch (%gearStatRoll)
				{
					case 0:	// Weapon damage.
						// Reduce stat.
						(%character.weapon).damage--;
						// Sanity check.
						if ((%character.weapon).damage < 1)
						{
							(%character.weapon).damage = 1;
						}
						// Update event log.
						updateEventText($squadColor @ %character.name @ $whiteColor @ " weapon " @ $damageColor @ "loses 1 damage" @ $defaultColor @ "!");
						
					case 1:	// Weapon range.
						// Reduce stat.
						(%character.weapon).range--;
						// Sanity check.
						if ((%character.weapon).range < 1)
						{
							(%character.weapon).range = 1;
						}
						// Update event log.
						updateEventText($squadColor @ %character.name @ $whiteColor @ " weapon " @ $damageColor @ "loses 1 range" @ $defaultColor @ "!");
						
					case 2:	// Weapon accuracy.
						// Reduce stat.
						(%character.weapon).accuracy--;
						// Sanity check.
						if ((%character.weapon).accuracy < 1)
						{
							(%character.weapon).accuracy = 1;
						}
						// Update event log.
						updateEventText($squadColor @ %character.name @ $whiteColor @ " weapon " @ $damageColor @ "loses 1 accuracy" @ $defaultColor @ "!");
						
					case 3:	// Armor armor rating.
						// Reduce stat.
						(%character.armor).accuracy--;
						// Sanity check.
						if ((%character.armor).accuracy < 1)
						{
							(%character.armor).accuracy = 1;
						}
						// Update event log.
						updateEventText($squadColor @ %character.name @ $whiteColor @ " armor " @ $damageColor @ "loses 1 armor" @ $defaultColor @ "!");
						
					case 4:	// Armor speed.
						// Reduce stat.
						(%character.armor).speed--;
						// Sanity check.
						if ((%character.armor).speed < 1)
						{
							(%character.armor).speed = 1;
						}
						// Update event log.
						updateEventText($squadColor @ %character.name @ $whiteColor @ " armor " @ $damageColor @ "loses 1 speed" @ $defaultColor @ "!");
				}
			}
		}
	}
}

// Spawns the specified trap.
function spawnTrap (%xIndex, %yIndex, %trapType)
{//echo("spawnTrap()");
	// Trap object.
	%trap = null;
	
	// Switch based on trap type.
	switch (%trapType)
	{
		case 0:	// "Standard" Trap.
			%trap = createLandmineAnimation(%xIndex, %yIndex);
			//%trap.setPosition(getTileShiftedPositionFromIndices(%xIndex, %yIndex));
			%trap.name = "Trap";
			%trap.xIndex = %xIndex;
			%trap.yIndex = %yIndex;
			%trap.trapType = %trapType;
			%trap.trapDamage = $standardTrapDamage;
	}
	
	// Save the newly spawned trap.
	$trapList.add(%trap);
}

// Spawns a random trap.
function spawnRandomTrap (%xIndex, %yIndex)
{//echo("spawnRandomTrap()");
	// Get a random trap type for the current dungeon type.
	%trapType = 0;
	%randomTrap = null;
	
	// Switch based on trap type.
	switch (%trapType)
	{
		case 0:	// "Standard" Trap.
			%randomTrap = createLandmineAnimation(%xIndex, %yIndex);
			//%randomTrap.setPosition(getTilePositionFromIndices(%xIndex, %yIndex));
			%randomTrap.name = "Trap";
			%randomTrap.xIndex = %xIndex;
			%randomTrap.yIndex = %yIndex;
			%randomTrap.trapType = %trapType;
			%randomTrap.trapDamage = $standardTrapDamage;
	}
	
	// Return the trap.
	return %randomTrap;
}

// Returns true iff the specified is free of traps.
function tileClearOfTraps (%xIndex, %yIndex)
{//echo("tileClearOfTraps()");
	// Loop through map items to see if character is on a trap.
	for (%i = 0; %i < $trapList.getCount(); %i++)
	{
		// Grab trap.
		%trap = $trapList.getObject(%i);
		
		if (%xIndex == %trap.xIndex	&&
			%yIndex == %trap.yIndex)
		{
			
			return false;
		}
	}
	return true;
}