// Handles new level zoning/generation.
// Worthless Bums 2012.


// Clean level launch.
function cleanLevelLaunch ()
{//echo("cleanLevelLaunch()");
	if (isEventPending($loadLevelEvent)		||
		isEventPending($generateLevelEvent))
	{
		if (!isEventPending($cleanLevelLaunchEvent))
		{
			$cleanLevelLaunchEvent = schedule(100, 0, "cleanLevelLaunch");
		}
	}
	else
	{//echo("$leaderImageMap =" SPC $leaderImageMap);
		cancelAllPendingEvents();
		// Spawn the current character in the new level.
		spawnPersistentCharacter();
		// Move squad to a free area!
		moveSquadToFreeArea();
		// Clears squad status effects.
		clearSquadStatusEffects();
		// Corrects stair placement.
		correctStairs();
	}
}

// Helper function to save persistent character data.
function savePersistentCharacterData ()
{//echo("savePersistentCharacterData()");
	// Check if the Squad Leader is alive.
	if ($leaderPersist)
	{//echo("Squad Leader is alive!");
		// General information.
		$leaderPersist = true;
		$leaderName = $playerSquad[0].name;
		$leaderLevel = getLevelFromExperience($playerSquad[0].experience);//$playerSquad[0].level;
		$leaderExperience = $playerSquad[0].experience;
		$leaderGender = $playerSquad[0].gender;
		$leaderImageMap = $playerSquad[0].imageMap;
		
		// Character health, armor, action points, statistics, skills, and inventory!
		// Health, Armor, and Action Points:
		$leaderCurrentHealth = $playerSquad[0].currentHealth;					// Character's current health.
		$leaderMaxHealth = $playerSquad[0].maxHealth;							// Character's maximum health.
		$leaderArmorRating = $playerSquad[0].armorRating;						// Character's armor rating.
		$leaderCurrentActionPoints = $playerSquad[0].currentActionPoints;		// Character's current health.
		$leaderMaxActionPoints = $playerSquad[0].maxActionPoints;				// Character's maximum health.
		// Statistics:
		$leaderPower = $playerSquad[0].power;									// Increases the power of bash and charge.
		$leaderSpeed = $playerSquad[0].speed;									// Increases movement, reload, and bomb placement speed.
		$leaderEndurance = $playerSquad[0].endurance;							// Increases health.
		// Skills:
		$leaderBash = $playerSquad[0].bash;										// By default the only skill a starting player has. Allows character to melee monsters and bash destructible objects.
		$leaderDemolitions = $playerSquad[0].demolitions;						// Used to activate explosives.
		$leaderArms = $playerSquad[0].arms;										// Allows character to use better ranged weapons.
		// Retraining:
		$leaderRetraining = $playerSquad[0].retraining;
		// Inventory:
		$leaderWeapon = ($playerSquad[0].weapon).weaponType;
		$leaderArmor = ($playerSquad[0].armor).armorType;
		$leaderammo = $playerSquad[0].ammo;
		// Kills:
		$leaderKills = $playerSquad[0].kills;
		// Talents:
		$leaderTalentPoints = $playerSquad[0].talentPoints;
		$leaderTalents = $playerSquad[0].talents;
		// Perks:
		$leaderPerks = $playerSquad[0].perks;
	}
	else
	{//echo("Squad Leader is NOT alive!");
		$leaderPersist = false;
	}
	
	// Check if the Scout is alive.
	if ($scoutPersist)
	{//echo("Squad Scout is alive!");
		// General information.
		$scoutPersist = true;
		$scoutName = $playerSquad[1].name;
		$scoutLevel = $playerSquad[1].level;
		$scoutExperience = $playerSquad[1].experience;
		$scoutGender = $playerSquad[1].gender;
		$scoutImageMap = $playerSquad[1].imageMap;
		
		// Character health, armor, action points, statistics, skills, and inventory!
		// Health, Armor, and Action Points:
		$scoutCurrentHealth = $playerSquad[1].currentHealth;					// Character's current health.
		$scoutMaxHealth = $playerSquad[1].maxHealth;							// Character's maximum health.
		$scoutArmorRating = $playerSquad[1].armorRating;						// Character's armor rating.
		$scoutCurrentActionPoints = $playerSquad[1].currentActionPoints;		// Character's current health.
		$scoutMaxActionPoints = $playerSquad[1].maxActionPoints;				// Character's maximum health.
		// Statistics:
		$scoutPower = $playerSquad[1].power;									// Increases the power of bash and charge.
		$scoutSpeed = $playerSquad[1].speed;									// Increases movement, reload, and bomb placement speed.
		$scoutEndurance = $playerSquad[1].endurance;							// Increases health.
		// Skills:
		$scoutBash = $playerSquad[1].bash;										// By default the only skill a starting player has. Allows character to melee monsters and bash destructible objects.
		$scoutDemolitions = $playerSquad[1].demolitions;						// Used to activate explosives.
		$scoutArms = $playerSquad[1].arms;										// Allows character to use better ranged weapons.
		// Retraining:
		$scoutRetraining = $playerSquad[1].retraining;
		// Inventory:
		$scoutWeapon = ($playerSquad[1].weapon).weaponType;
		$scoutArmor = ($playerSquad[1].armor).armorType;
		$scoutammo = $playerSquad[1].ammo;
		// Kills:
		$scoutKills = $playerSquad[1].kills;
		// Talents:
		$scoutTalentPoints = $playerSquad[1].talentPoints;
		$scoutTalents = $playerSquad[1].talents;
		// Perks:
		$scoutPerks = $playerSquad[1].perks;
	}
	else
	{//echo("Squad Scout is NOT alive!");
		$scoutPersist = false;
	}
	
	// Check if the Grenadier is alive.
	if ($grenadierPersist)
	{//echo("Squad Grenadier is alive!");
		// General information.
		$grenadierPersist = true;
		$grenadierName = $playerSquad[2].name;
		$grenadierLevel = $playerSquad[2].level;
		$grenadierExperience = $playerSquad[2].experience;
		$grenadierGender = $playerSquad[2].gender;
		$grenadierImageMap = $playerSquad[2].imageMap;
		
		// Character health, armor, action points, statistics, skills, and inventory!
		// Health, Armor, and Action Points:
		$grenadierCurrentHealth = $playerSquad[2].currentHealth;					// Character's current health.
		$grenadierMaxHealth = $playerSquad[2].maxHealth;							// Character's maximum health.
		$grenadierArmorRating = $playerSquad[2].armorRating;						// Character's armor rating.
		$grenadierCurrentActionPoints = $playerSquad[2].currentActionPoints;		// Character's current health.
		$grenadierMaxActionPoints = $playerSquad[2].maxActionPoints;				// Character's maximum health.
		// Statistics:
		$grenadierPower = $playerSquad[2].power;									// Increases the power of bash and charge.
		$grenadierSpeed = $playerSquad[2].speed;									// Increases movement, reload, and bomb placement speed.
		$grenadierEndurance = $playerSquad[2].endurance;							// Increases health.
		// Skills:
		$grenadierBash = $playerSquad[2].bash;										// By default the only skill a starting player has. Allows character to melee monsters and bash destructible objects.
		$grenadierDemolitions = $playerSquad[2].demolitions;						// Used to activate explosives.
		$grenadierArms = $playerSquad[2].arms;										// Allows character to use better ranged weapons.
		// Retraining:
		$grenadierRetraining = $playerSquad[2].retraining;
		// Inventory:
		$grenadierWeapon = ($playerSquad[2].weapon).weaponType;
		$grenadierArmor = ($playerSquad[2].armor).armorType;
		$grenadierammo = $playerSquad[2].ammo;
		// Kills:
		$grenadierKills = $playerSquad[2].kills;
		// Talents:
		$grenadierTalentPoints = $playerSquad[2].talentPoints;
		$grenadierTalents = $playerSquad[2].talents;
		// Perks:
		$grenadierPerks = $playerSquad[2].perks;
	}
	else
	{//echo("Squad Grenadier is NOT alive!");
		$grenadierPersist = false;
	}
	
	// Check if the Support is alive.
	if ($supportPersist)
	{//echo("Squad Support is alive!");
		// General information.
		$supportPersist = true;
		$supportName = $playerSquad[3].name;
		$supportLevel = $playerSquad[3].level;
		$supportExperience = $playerSquad[3].experience;
		$supportGender = $playerSquad[3].gender;
		$supportImageMap = $playerSquad[3].imageMap;
		
		// Character health, armor, action points, statistics, skills, and inventory!
		// Health, Armor, and Action Points:
		$supportCurrentHealth = $playerSquad[3].currentHealth;					// Character's current health.
		$supportMaxHealth = $playerSquad[3].maxHealth;							// Character's maximum health.
		$supportArmorRating = $playerSquad[3].armorRating;						// Character's armor rating.
		$supportCurrentActionPoints = $playerSquad[3].currentActionPoints;		// Character's current health.
		$supportMaxActionPoints = $playerSquad[3].maxActionPoints;				// Character's maximum health.
		// Statistics:
		$supportPower = $playerSquad[3].power;									// Increases the power of bash and charge.
		$supportSpeed = $playerSquad[3].speed;									// Increases movement, reload, and bomb placement speed.
		$supportEndurance = $playerSquad[3].endurance;							// Increases health.
		// Skills:
		$supportBash = $playerSquad[3].bash;									// By default the only skill a starting player has. Allows character to melee monsters and bash destructible objects.
		$supportDemolitions = $playerSquad[3].demolitions;						// Used to activate explosives.
		$supportArms = $playerSquad[3].arms;									// Allows character to use better ranged weapons.
		// Retraining:
		$supportRetraining = $playerSquad[3].retraining;
		// Inventory:
		$supportWeapon = ($playerSquad[3].weapon).weaponType;
		$supportArmor = ($playerSquad[3].armor).armorType;
		$supportammo = $playerSquad[3].ammo;
		// Kills:
		$supportKills = $playerSquad[3].kills;
		// Talents:
		$supportTalentPoints = $playerSquad[3].talentPoints;
		$supportTalents = $playerSquad[3].talents;
		// Perks:
		$supportPerks = $playerSquad[3].perks;
	}
	else
	{//echo("Squad Support is NOT alive!");
		$supportPersist = false;
	}
}

// Generates a level from load data.
function generateLoadLevel ()
{//echo("generateLoadLevel()");
	// Reset stairs found flag.
	$squadFoundStairs = false;
	
	// Sets the file to directory path: "C:\Users\<user>\AppData\Roaming\Steam Marines\"
	//%filePath = expandFilename($UserDirectory @ "/Worthless Bums/Steam Marines/" @ "save" @ ".sav");
	%filePath = getSaveGameFilePath();
	// The save file object.
	%saveFile = new fileobject();
	// Check the file open status.
	%ret = %saveFile.OpenForRead(%filePath);
	// Can't open the file.
	if (!%ret)
	{//echo("Bad save file!");
		error("Invalid save file!");
		return false;
	}
	// Load the level data.
	$generateLevelEvent = loadCurrentLevel(%saveFile);
	// Load the lifted level data.
	$generateLevelEvent = loadCurrentLiftedLevel(%saveFile);		// Memory leak here!
	// Close the save file.
	%saveFile.close();
}

// Generates a random level.
// This function should generate dungeon types based on the value of $overworldLocation.
function generateRandomLevel ()
{//echo("generateRandomLevel()");//echo("$overworldLocation =" SPC $overworldLocation);
	// Reset stairs found flag.
	$squadFoundStairs = false;
	
	// Irregular deck generation parameters.
	$failThreshold = 110;
	$featureProbability = 50;
	$numberOfRooms = 20 + $dungeonLevel * 20;
	$iterations = $dungeonLevel * 50;
	
	// Dungeon dimension.
	%dungeonDimension = $mazeDimension;
	// Dispatch by dungeon specified in $overworldLocation.
	switch$ ($overworldLocation)
	{
		case "Command Deck":		$generateLevelEvent = generateSpecifiedIrregularDungeon(%dungeonDimension, "PreloadedCommandDeckImageMap", 		"MetalTilesWallImageMap", $failThreshold, $featureProbability, $numberOfRooms, $iterations, false);
		case "Engineering Deck":	$generateLevelEvent = generateSpecifiedIrregularDungeon(%dungeonDimension, "PreloadedEngineeringDeckImageMap",	"MetalTilesWallImageMap", $failThreshold, $featureProbability, $numberOfRooms, $iterations, false);
		case "Medical Deck":		$generateLevelEvent = generateSpecifiedIrregularDungeon(%dungeonDimension, "PreloadedMedicalDeckImageMap", 		"MetalTilesWallImageMap", $failThreshold, $featureProbability, $numberOfRooms, $iterations, false);
		case "Armory Deck":			$generateLevelEvent = generateSpecifiedIrregularDungeon(%dungeonDimension, "PreloadedArmoryDeckImageMap", 		"MetalTilesWallImageMap", $failThreshold, $featureProbability, $numberOfRooms, $iterations, false);
		case "Bridge Deck":			$generateLevelEvent = generateSpecifiedIrregularDungeon(%dungeonDimension, "PreloadedBridgeDeckImageMap", 		"MetalTilesWallImageMap", $failThreshold, $featureProbability, $numberOfRooms, $iterations, false);
		case "Alien Deck":			$generateLevelEvent = generateSpecifiedIrregularDungeon(%dungeonDimension, "PreloadedAlienDeckImageMap", 		"MetalTilesWallImageMap", $failThreshold, $featureProbability, $numberOfRooms, $iterations, false);
	}
	
	// Corrects any misplaced doors.
	correctDoors();
	
	// Spawn an elevator disruptor.
	if ($difficultyLevel >= 3	&&		// Difficulty must be at least "Brutal" to spawn disruptors!
		$DisruptorList.getCount() <= 0)	// Only one disruptor per level!
	{
		spawnDisruptor();
	}
	
	// Play level music.
	playLevelMusic();
}
function playLevelMusic ()
{//echo("playLevelMusic()");
	// Dispatch by dungeon specified in $overworldLocation.
	switch$ ($overworldLocation)
	{
		case "Command Deck":		playCommandDeckMusic();
		case "Engineering Deck":	playEngineeringDeckMusic();
		case "Medical Deck":		playMedicalDeckMusic();
		case "Armory Deck":			playArmoryDeckMusic();
		case "Bridge Deck":			playBridgeDeckMusic();
		case "Alien Deck":			playAlienDeckMusic();
	}
}
// Brings the party to the next level.
function nextDungeonLevel ()
{//echo("nextDungeonLevel()");echo("$leaderPersist =" SPC $leaderPersist);
	// Save persistent data.
	savePersistentCharacterData();
	// Need to save peristent squad inventory!
	savePersistentSquadInventory();
	// End level.
	sceneWindow2D.endLevel();											// This wipes out $playerSquad[$activeCharacter]! Save this data prior to this code!
	// Cancel all pending events.
	cancelAllPendingEvents();
	// Schedule continue next dungeon level.
	//schedule(100, "continueNextDungeonLevel");
	continueNextDungeonLevel();
}

function continueNextDungeonLevel ()
{//echo("continueNextDungeonLevel()");
	$loadLevelEvent = startGame($Game::DefaultScene);
	// Generate a new level.
	generateRandomLevel();
	// Make sure we get a clean level launch with level/dungeon/monster/player generation and spawns.
	cleanLevelLaunch();
	// Display dungeon level message in event log.
	showDungeonLevelMessage();
}

// Displays a message depending on current dungeon type and level.
function showDungeonLevelMessage ()
{//echo("showDungeonLevelMessage()");
	// Synchronize dungeon levels before messaging!
	syncDungeonLevels();
	
	// Update event log.
	updateEventText($friendlyActionColor @ "Squad descends to " @ $defaultColor @ $overworldLocation @ " Level " @ $dungeonLevel @ ".");
}