// Handles Treasure Chest spawning.
// Worthless Bums 2012.


// Spawns a treasure chest on the current squad member's position.
// FOR TESTING PURPOSES ONLY!
function stc ()
{//echo("stc()");
	// Treasure Chest sim set.
	if (isObject($treasureChestList))
	{
		$treasureChestList.safeDelete();
	}
	$treasureChestList = new SimSet();
	
	// Randomize loot type.
	%lootType = getRandom(0, 1);
	//%lootType = 1;		// For testing purposes only!
	// Weapon.
	if (%lootType == 0)
	{
		// Create weapon loot for the treasure chest.
		%loot = createRandomWeapon(getRandom(0, 3), $dungeonLevel, $weaponProjectileBallisticType);	// Create any random weapon for any squad member type given the current dungeon level.
	}
	// Armor.
	else if (%lootType == 1)
	{
		// Create armor loot for the treasure chest.
		%loot = createRandomArmor(getRandom(0, 3), $dungeonLevel);	// Create any random armor for any squad member type given the current dungeon level.
	}
	
	// Create new treasure chest animation.
	%tilePosition = getTilePositionFromIndices($playerSquad[$activeCharacter].xIndex, $playerSquad[$activeCharacter].yIndex);
	%treasureAnimation = new Sprite("Treasure Chest")
	{
		SceneLayer = 15;
		position = getWord(%tilePosition, 0) SPC getWord(%tilePosition, 0) + $GlobalVerticalShift;
		scenegraph = levelSceneGraph;
		image = "Sprites:ContainerChest";
		visible = true;
		size = "4 4";
		loot = %loot;
		lootType = %lootType;
	};
	addObjectToScene(%treasureAnimation);
	createUnitShadow(%treasureAnimation);
	$treasureChestList.add(%treasureAnimation);
}


// Returns true iff there is a treasure chest on the specified tile.
function isTreasureChestOnTile (%xIndex, %yIndex)
{//echo("isTreasureChestOnTile()");
	// Make sure $treasureChestList exists.
	if (!isObject($treasureChestList)	||
		$treasureChestList.getCount() <= 0)
	{
		return false;
	}
	for (%i = 0; %i < $treasureChestList.getCount(); %i++)
	{
		%treasure = $treasureChestList.getObject(%i);
		if (%treasure.xIndex == %xIndex	&&
			%treasure.yIndex == %yIndex)
		{
			return true;
		}
	}
	return false;
}
// Grabs the treasure on the specified tile.
function getTreasureOnTile (%xIndex, %yIndex)
{//echo("getTreasureOnTile()");
	// Make sure $treasureChestList exists.
	if (!isObject($treasureChestList)	||
		$treasureChestList.getCount() <= 0)
	{
		return false;
	}
	
	// Convert indices to position.
	%tilePosition = getTilePositionFromIndices(%xIndex, %yIndex);
	
	// Loop through $treasureChestList and check their positions.
	for (%i = 0; %i < $treasureChestList.getCount(); %i++)
	{//echo("%i =" SPC %i);echo("%treasurePosition =" SPC %treasurePosition);echo("%tilePosition =" SPC %tilePosition);
		%treasure = ($treasureChestList.getObject(%i));
		%treasurePosition = %treasure.getPosition();
		if (%treasure.xIndex == %xIndex	&&
			%treasure.yIndex == %yIndex)
		{
			// Grab the loot and loot type before deletion.
			%loot = ($treasureChestList.getObject(%i)).loot;
			%lootType = ($treasureChestList.getObject(%i)).lootType;
			// Check for max inventory!
			if ($squadInventory.getCount() >= $squadInventoryMaxItems)
			{
				playAudio("Audio:inventoryFull", EffectsAudioVolume.value);
				updateEventText($whiteColor @ "Inventory is full" @ $defaultColor @ "!");
				return false;
			}
			$GlobalStats.totalChestsOpened++;
			($treasureChestList.getObject(%i)).safeDelete();
			if (%treasure.image $= "Sprites:ContainerChest")
			{
				playAudio("Audio:treasureFound", EffectsAudioVolume.value);
				%itemType = getRandomTreasureItemType();
				%item = createRandomItem(%itemType, getTilePositionFromIndices(9999, 9999), 9999, 9999);
				addItemToInventory(%item, 0);		// Second parameter just has to not be -1 /-2 which indicates weapons/armor!
				updateEventText("Found " @ $itemColor @ getItemName(%itemType) @ $defaultColor @ "!");
				triggerContextSensitiveUI(true);
				return true;
			}
			// Dispatch based on loot type.
			// Weapon.
			if (%lootType == 0)
			{//echo("loot type is WEAPON!");
				// Get loot class.
				%lootName = getWord(%loot, 0);
				%lootClass = getWord(%loot, 1);
				%classDispatch = %lootClass;
				%lootClass = "";
				switch (%classDispatch)
				{
					case 0:	%lootClass = "Leader";
					case 1:	%lootClass = "Scout";
					case 2:	%lootClass = "Grenadier";
					case 3:	%lootClass = "Support";
					case 4:	%lootClass = "Engineer";
				}
				if (%lootClass $= "")
				{
					updateEventText($whiteColor @ "Chest was empty" @ $defaultColor @ "!");
					return false;
				}
				else
				{
					playAudio("Audio:treasureFound", EffectsAudioVolume.value);
					updateEventText("Found a " @ $itemColor @ %lootName @ $defaultColor @ " weapon for the " @ $squadColor @ %lootClass @ " class" @ $defaultColor @ "!");
					addItemToInventoryFromChest(%loot, -1);
					triggerContextSensitiveUI(true);
					return true;
				}
			}
			// Armor
			else if (%lootType == 1)
			{
				// Get loot class.
				%lootName = getWord(%loot, 0);
				%lootClass = getWord(%loot, 1);
				%classDispatch = %lootClass;
				%lootClass = "";
				switch (%classDispatch)
				{
					case 0:	%lootClass = "Leader";
					case 1:	%lootClass = "Scout";
					case 2:	%lootClass = "Grenadier";
					case 3:	%lootClass = "Support";
					case 4:	%lootClass = "Engineer";
				}
				if (%lootClass $= "")
				{
					updateEventText($whiteColor @ "Chest was empty" @ $defaultColor @ "!");
					return false;
				}
				else
				{
					playAudio("Audio:treasureFound", EffectsAudioVolume.value);
					updateEventText("Found a " @ $itemColor @ %lootName @ $defaultColor @ " armor for the " @ $squadColor @ %lootClass @ " class" @ $defaultColor @ "!");
					addItemToInventoryFromChest(%loot, -2);
					triggerContextSensitiveUI(true);
					return true;
				}
			}
		}
	}
	return false;
}
// Checks if the specified tile is clear of treasure chests.
function tileClearOfTreasure (%xIndex, %yIndex)
{//echo("tileClearOfTreasure()");
	// Make sure $treasureChestList exists.
	if (!isObject($treasureChestList)	||
		$treasureChestList.getCount() <= 0)
	{
		return true;
	}
	// Convert indices to position.
	%tilePosition = getTilePositionFromIndices(%xIndex, %yIndex);
	// Loop through $treasureChestList and check there positions.
	for (%i = 0; %i < $treasureChestList.getCount(); %i++)
	{
		// Get the treasure's position.
		%treasure = ($treasureChestList.getObject(%i));
		%treasurePosition = %treasure.getPosition();
		// Check the treasure position against the specified tile position.
		if (%treasurePosition == %tilePosition)
		{
			return false;
		}
	}
	return true;
}
// Clears treasure chests on the map.
function clearTreasureChests ()
{//echo("clearTreasureChests()");
	// Treasure Chest sim set.
	if (isObject($treasureChestList))
	{
		$treasureChestList.safeDelete();
	}
	// Spawn them randomly on free tiles.
	for (%i = 0; %i < %treasureSpawnCount; %i++)
	{
		($treasureChestList.getObject(%i)).safeDelete();
	}
}
// Spawns treasure chests on the map.
function spawnTreasureChests ()
{//echo("spawnTreasureChests()");
	if ($overworldLocation $= "Alien Deck")
	{
		return;
	}
	// Treasure Chest sim set.
	if (isObject($treasureChestList))
	{
		//$treasureChestList.safeDelete();
		for (%i = 0; %i < $treasureChestList.getCount(); %i++)
		{
			// Grab treasure.
			%treasure = $treasureChestList.getObject(%i);
			// Delete it.
			%treasure.safeDelete();
		}
	}
	// Create new treasure chest sim set.
	$treasureChestList = new SimSet();
	// Pick a random amount of treasure chests to spawn.
	%treasureSpawnCount = $baseTreasureSpawn;// + getRandom(0, $dungeonLevel);		// Kind of arbitrary...
	%actualTreasureSpawnCount = 0;
	// Spawn them randomly on free tiles.
	for (%i = 0; %i < %treasureSpawnCount; %i++)
	{
		%counter = 0;
		// Beware infinite loops!
		while (%actualTreasureSpawnCount == %i)
		{//echo("%actualTreasureSpawnCount =" SPC %actualTreasureSpawnCount);
			%xIndex = getRandom(0, $mazeDimension - 1);
			%yIndex = getRandom(0, $mazeDimension - 1);
			%tilePosition = getTilePositionFromIndices(%xIndex, %yIndex);
			
			if (!isObject($mazeRoom[%xIndex, %yIndex])		&&
				tileClearOfSquadMembers(%xIndex, %yIndex)	&&
				tileClearOfMonsters(%xIndex, %yIndex)		&&
				tileClearOfItems(%xIndex, %yIndex)			&&
				tileClearOfTreasure(%xIndex, %yIndex)		&&
				!isSpaceTile(%xIndex, %yIndex))
			{
				// Spawn treasure chest.
				spawnTreasureChest(%xIndex, %yIndex);
				
				// Increment treasure spawn count.
				%actualTreasureSpawnCount++;
			}
			%counter++;
			// Just break out after X iterations.
			if (%counter > 50)
			{
				
				return false;
			}
		}
	}
}
// Spawns a treasure chest at the specified indices.
function spawnTreasureChest (%xIndex, %yIndex)
{//echo("spawnTreasureChest()");
	// Randomize loot type.
	%lootType = getRandom(0, 9);//getRandom(2, 9);	// Don't spawn weapons and armor for now!
	// Calculate position from indices.
	%tilePosition = getTilePositionFromIndices(%xIndex, %yIndex);
	%image = "Sprites:ContainerChest";
	// Small chance to spawn weapon and armor chests!
	if (getRandom(1, 100) <= 4)
	{
		%lootType = getRandom(0, 1);
	}
	//%lootType = 0;	// For testing purposes only!
	// Weapon.
	if (%lootType == 0)
	{
		// Create weapon loot for the treasure chest.
		%loot = createRandomWeapon(getRandom(0, 4), $dungeonLevel, $weaponProjectileBallisticType);	// Create any random weapon for any squad member type given the current dungeon level.
		%image = "Sprites:ContainerChestRed";
	}
	// Armor.
	else if (%lootType == 1)
	{
		// Create armor loot for the treasure chest.
		%loot = createRandomArmor(getRandom(0, 4), $dungeonLevel);	// Create any random armor for any squad member type given the current dungeon level.
		%image = "Sprites:ContainerChestBlue";
	}
	%treasureChest = new Sprite("Treasure Chest")
	{
		SceneLayer = $TreasureChestLayer;//15;
		position = %tilePosition;
		scenegraph = levelSceneGraph;
		image = %image;
		visible = true;
		size = "4 4";
		loot = %loot;
		lootType = %lootType;
		xIndex = %xIndex;
		yIndex = %yIndex;
	};
	addObjectToScene(%treasureChest);
	// Add the treasure chest to the sim set.
	$treasureChestList.add(%treasureChest);
}