-- Main loop for the entire game

RaceManager:SetRaceDuration(GameSettings.roundDuration)
while true do
	-- Only enter 'Waiting for Players' loop if there are not enough players to start
	-- a round
	if #PlayerManager.ActivePlayers < GameSettings.minimumPlayers then
		RaceManager:SetRaceStatus(RaceManager.Status.WaitingForPlayers)

		DisplayManager.updateTime(0)
		PlayerManager.MiminumActivePlayers:Wait()
	end

	-- Actual Intermission
	gameTimer:stop()
	RaceManager:SetRaceStatus(RaceManager.Status.WaitingForRaceToStart)
	gameTimer:start(GameSettings.intermissionDuration)
	DisplayManager.trackTimer(gameTimer)
	gameTimer.finished:Wait()
	
	-- Prepare players at start of race and start countdown
	PlayerManager:PreparePlayers()
	RaceManager:SetRaceStatus(RaceManager.Status.Countdown)
		
	gameTimer:stop()
	gameTimer:start(GameSettings.countdownDuration)
	DisplayManager.trackTimer(gameTimer)
	gameTimer.finished:Wait()
	
	-- Start the race
	PlayerManager:StartPlayer()
	RaceManager:SetRaceStatus(RaceManager.Status.RoundInProgress)

	gameTimer:stop()
	gameTimer:start(GameSettings.roundDuration)
	DisplayManager.trackTimer(gameTimer)
	RaceManager:Start(PlayerManager.ActivePlayers)
	
	-- Waits until the roundEnd event has fired before continuing the script
	local resultString, raceFinished
	raceFinished = RaceManager.RaceFinished:Connect(function(winner)
		if winner then
			resultString = "WINNER: "..winner.Name
			LeaderboardManager:incrementStat(winner, "Wins")
		else
			resultString = "NOBODY WON!"
		end
		raceFinished:Disconnect()
	end)
	RaceManager.RaceFinished:wait()
	DisplayManager.updateTime(0)
	
	repeat wait() until resultString
	local timeLeft = gameTimer:getTimeLeft() or 0
	local resultTime = GameSettings.roundDuration - timeLeft
	gameTimer:stop()
	PlayerManager:DisplayRoundResult(resultString, resultTime)
	
	gameTimer:start(GameSettings.transitionEnd)
	DisplayManager.trackTimer(gameTimer)

	-- Starts the end intermission
	RaceManager:SetRaceStatus(RaceManager.Status.RoundOver)
	
	wait(GameSettings.transitionEnd)
	
	-- Resets the game by moving players back into the lobby and clearing used variables 
	PlayerManager:ResetPlayers()	
end

