// Door Handler.
// Worthless Bums 2013.


// Helper function that returns the tile indices adjacent in the direction the specified unit is facing.
function getFacingAdjacentTile (%unit)
{//echo("getFacingAdjacentTile()");
	switch (%unit.facing)
	{
		case $northDirection:	return %unit.xIndex SPC (%unit.yIndex - 1);
		case $southDirection:	return %unit.xIndex SPC (%unit.yIndex + 1);
		case $eastDirection:	return (%unit.xIndex + 1) SPC %unit.yIndex;
		case $westDirection:	return (%unit.xIndex - 1) SPC %unit.yIndex;
	}
}
// Trigger on a door being opened.
function openDoorTrigger (%xIndex, %yIndex, %unit)
{//echo("openDoorTrigger()");
	if ($generateTutorialLevel)
	{
		if ($tutorialSection == 0)
		{
			tutorialMessage1();
		}
	}
	if (isObject($mazeRoom[%xIndex, %yIndex].plasticExplosive))
	{
		if (%unit.demolitions > 0)
		{
			if (getRandom(1, 100) <= %unit.demolitions * 25)
			{
				%item = createRandomItem(20, getTilePositionFromIndices(%unit.xIndex, %unit.yIndex), %unit.xIndex, %unit.yIndex);
				updateEventText($itemColor @ "Plastic explosives" @ $friendlyActionColor @ " diffused" @ $defaultColor @ "!");
				if ($squadInventory.getCount() < $squadInventoryMaxItems)
				{
					addItemToInventory(%item, 0);		// Second parameter just has to not be -1 /-2 which indicates weapons/armor!
					updateEventText($itemColor @ "Plastic explosives" @ $friendlyActionColor @ " added to " @ $squadColor @ "inventory" @ $defaultColor @ "!");
				}
				else
				{
					$mapItems.add(%item);
					updateEventText($itemColor @ "Plastic explosives" @ $friendlyActionColor @ " dropped on " @ $whiteColor @ "floor" @ $defaultColor @ "!");
				}
				($mazeRoom[%xIndex, %yIndex].plasticExplosive).safeDelete();
				updateInventoryTabInformation();
				return;
			}
		}
		grenadeEmptyAoePathDamage(%xIndex, %yIndex, $northDirection);	// Direction is irrelevant at the moment!
		grenadierDestroyTile(%xIndex, %yIndex);
		updateSquadMemberFloatingHealthPoints();
		updateAllMonstersFloatingHealthPointText();
		updateEventText($itemColor @ "Plastic explosives" @ $hostileActionColor @ " detonated" @ $defaultColor @ "!");
		($mazeRoom[%xIndex, %yIndex].plasticExplosive).safeDelete();
	}
}
// Returns true iff the specified tile is a door.
function isDoorTile (%xIndex, %yIndex)
{//echo("isDoorTile()");
	return (isClosedDoorTile(%xIndex, %yIndex)	||	isOpenedDoorTile(%xIndex, %yIndex));
}
// Returns true iff the specified tile is a door.
function isClosedDoorTile (%xIndex, %yIndex)
{//echo("isClosedDoorTile()");
	if ($mazeRoom[%xIndex, %yIndex].status == -3)
	{
		return true;
	}
	return false;
}
// Returns true iff the specified tile is a door.
function isOpenedDoorTile (%xIndex, %yIndex)
{//echo("isOpenedDoorTile()");
	if ($mazeRoom[%xIndex, %yIndex].status == -4)
	{
		return true;
	}
	return false;
}