/**
 *	Rounds mode
 */
#Extends "Modes/TrackMania/Base/RoundsBase2.Script.txt"

#Const CompatibleMapTypes	"Race"
#Const Version							"2017-03-09"
#Const ScriptName						"Modes/TrackMania/Rounds/Rounds.Script.txt"

// ---------------------------------- //
// Libraries
// ---------------------------------- //
#Include "TextLib" as TL

// ---------------------------------- //
// Settings
// ---------------------------------- //
#Setting S_PointsLimit			50
#Setting S_UseTieBreak			True	as _("Use tie-break :")	///< Continue to play the map until the tie is broken
#Setting S_WarmUpNb				0	as _("Number of warm up :")
#Setting S_WarmUpDuration	0	as _("Duration of one warm up :")

#Setting S_ScriptEnvironment "production"/*/"development"*/

// ---------------------------------- //
// Constants
// ---------------------------------- //
#Const C_BotsNb 0
#Const C_HudModulePath "Nadeo/TrackMania/Rounds/Hud.Module.Gbx" ///< Path to the hud module
#Const C_ManiaAppUrl "file://Media/ManiaApps/Nadeo/TrackMania/Rounds/Rounds.Script.txt"

#Const Description _("""$fffIn $f00Rounds$fff mode, the goal is to win a maximum number of $f00points.

$fffThe rounds mode consists of $f00a series of races$fff.
When you finish a race in a good $f00position$fff, you get $f00points$fff, added to your total.

The $f00winner$fff is the first player whose total reaches the $f00point limit$fff (30 for example).""")

// ---------------------------------- //
// Extends
// ---------------------------------- //
***Match_LogVersion***
***
MB_LogVersion(ScriptName, Version);
***

***Match_Settings***
***
MB_Settings_UseDefaultHud = False;
***

***Match_Rules***
***
ModeInfo::SetName("Rounds");
ModeInfo::SetType(ModeInfo::C_Type_FreeForAll);
ModeInfo::SetRules(Description);
ModeInfo::SetStatusMessage("");
***

***Match_LoadHud***
***
ClientManiaAppUrl = C_ManiaAppUrl;
Hud_Load(C_HudModulePath);
MB_SortScores(CTmMode::ETmScoreSortOrder::TotalPoints);
***

***Match_InitServer***
***
declare PrevPointsLimit = -1;
***

***Match_StartMap***
***
// ---------------------------------- //
// Initialize map
Users_SetNbFakeUsers(C_BotsNb, 0);

// ---------------------------------- //
// Warm up
declare WarmUpDuration = S_WarmUpDuration * 1000;
MB_WarmUp(S_WarmUpNb, WarmUpDuration);
***

***Match_PlayLoop***
***
// ---------------------------------- //
// Manage events
foreach (Event in PendingEvents) {
	Events::Valid(Event);
	
	// ---------------------------------- //
	// Waypoint
	if (Event.Type == CTmModeEvent::EType::WayPoint) {
		if (Event.IsEndRace) {
			declare Better = Scores::SetPlayerBestRaceIfBetter(Event.Player.Score, Event.Player.CurRace, CTmResult::ETmRaceResultCriteria::Time);
			Scores::SetPlayerPrevRace(Event.Player.Score, Event.Player.CurRace);
			ComputeLatestRaceScores();
			MB_SortScores(CTmMode::ETmScoreSortOrder::TotalPoints);
			TM::EndRace(Event.Player);
			
			// ---------------------------------- //
			// Start the countdown if it's the first player to finish
			if (CutOffTimeLimit <= 0) {
				CutOffTimeLimit = GetFinishTimeout();
			}
		}
		if (Event.IsEndLap) {
			declare Better = Scores::SetPlayerBestLapIfBetter(Event.Player.Score, Event.Player.CurLap, CTmResult::ETmRaceResultCriteria::Time);
		}
	}
	// ---------------------------------- //
	// GiveUp
	else if (Event.Type == CTmModeEvent::EType::GiveUp) {
		TM::WaitRace(Event.Player);
	}
}

// ---------------------------------- //
// Server info change
if (PrevPointsLimit != S_PointsLimit) {
	PrevPointsLimit = S_PointsLimit;
	if (Hud != Null) Hud.ScoresTable.SetFooterText(TL::Compose("%1 "^S_PointsLimit, _("Points limit : ")));
}
***

***Match_EndRound***
***
TM::WaitRaceAll();
CutOffTimeLimit = -1;

if (ForceEndRound) {
	ForcedEndRoundSequence();
} else {
	// Get the last round points
	ComputeLatestRaceScores();
	MB_SortScores(CTmMode::ETmScoreSortOrder::TotalPoints);
	UIManager.UIAll.ScoreTableVisibility = CUIConfig::EVisibility::ForcedVisible;
	UIManager.UIAll.UISequence = CUIConfig::EUISequence::EndRound;
	MB_Sleep(3000);
	// Add them to the total scores
	ComputeScores();
	MB_SortScores(CTmMode::ETmScoreSortOrder::TotalPoints);
	MB_Sleep(3000);
	UIManager.UIAll.ScoreTableVisibility = CUIConfig::EVisibility::Normal;
	UIManager.UIAll.UISequence = CUIConfig::EUISequence::Playing;
	
	if (MapIsOver()) MB_StopMap();
}
***

***Match_EndMap***
***
MB_SortScores(CTmMode::ETmScoreSortOrder::TotalPoints);
Scores::SetDefaultLadderSort(Scores::C_Sort_MapPoints);
Scores::SetPlayerWinner(Scores::GetBestPlayer(Scores::C_Sort_MapPoints, Scores::Order_Descending()));
***

// ---------------------------------- //
// Functions
// ---------------------------------- //
// ---------------------------------- //
/** Get the time left to the players to finish the round after the first player
 *
 *	@return 		The time left in ms
 */
Integer GetFinishTimeout() {
	declare FinishTimeout = 0;
	
	if (S_FinishTimeout >= 0) {
		FinishTimeout = S_FinishTimeout * 1000;
	} else {
		FinishTimeout = 5000;
		if (Map.TMObjective_IsLapRace && NbLaps > 0 && Map.TMObjective_NbLaps > 0) {
			FinishTimeout += ((Map.TMObjective_AuthorTime / Map.TMObjective_NbLaps) * NbLaps) / 6;
		} else {
			FinishTimeout += Map.TMObjective_AuthorTime / 6;
		}
	}
	
	if (S_UseAlternateRules) {
		if (Map.TMObjective_IsLapRace && NbLaps > 0 && Map.TMObjective_NbLaps > 0) {
			return G_RoundStartTime + ((Map.TMObjective_AuthorTime / Map.TMObjective_NbLaps) * NbLaps) + FinishTimeout;
		} else {
			return G_RoundStartTime + Map.TMObjective_AuthorTime + FinishTimeout;
		}
	} else {
		return Now + FinishTimeout;
	}
	
	// Default value from TMO, TMS (not used)
	return Now + 15000;
}

// ---------------------------------- //
/// Compute the latest race scores
Void ComputeLatestRaceScores() {
	MB_SortScores(CTmMode::ETmScoreSortOrder::PrevRace_Time);
	
	// Only points for the first players
	if (S_UseAlternateRules) {
		declare Points = 1;
		
		foreach (Score in Scores) {
			if (Scores::GetPlayerPrevRaceTime(Score) > 0) {
				//Score.PrevRaceDeltaPoints = Points;
				Scores::SetPlayerRoundPoints(Score, Points);
				if (Points > 0) Points -= 1;
			} else {
				//Score.PrevRaceDeltaPoints = 0;
				Scores::SetPlayerRoundPoints(Score, 0);
			}
		}
	} 
	// Points distributed between all players
	else {		
		declare I = 0;
		foreach (Score in Scores) {
			if (Scores::GetPlayerPrevRaceTime(Score) > 0) {
				declare Points = 0;
				declare PointsRepartition = Scores::GetPointsRepartition();
				if (PointsRepartition.count > 0) {
					if (PointsRepartition.existskey(I)) {
						Points = PointsRepartition[I];
					} else {
						Points = PointsRepartition[PointsRepartition.count - 1];
					}
				}
				//Score.PrevRaceDeltaPoints = Points;
				Scores::SetPlayerRoundPoints(Score, Points);
				I += 1;
			} else {
				//Score.PrevRaceDeltaPoints = 0;
				Scores::SetPlayerRoundPoints(Score, 0);
			}
		}
	}
}

// ---------------------------------- //
/// Compute the map scores
Void ComputeScores() {
	/*foreach (Score in Scores) {
		Score.Points += Score.PrevRaceDeltaPoints;
		Score.PrevRaceDeltaPoints = 0;
	}*/
	Scores::EndRound();
}

// ---------------------------------- //
/** Check if we should go to the next map
 *
 *	@return		True if it is the case, false otherwise
 */
Boolean MapIsOver() {
	declare MaxScore = -1;
	declare Tie = False;
	foreach (Score in Scores) {
		declare MapPoints = Scores::GetPlayerMapPoints(Score);
		if (MapPoints > MaxScore) {
			MaxScore = MapPoints;
			Tie = False;
		} else if (MapPoints == MaxScore) {
			Tie = True;
		}
	}
	
	if (S_UseTieBreak && Tie) return False;
	if (MaxScore >= S_PointsLimit) return True;
		
	return False;
}