--[[
	Function called upon entering the state - creates the systems, and initialises the game loop.
]]

function ServerGame.onEnter(stateMachine, event, from, to)
	SystemManager.createSystems()

	local engine = SystemManager.getSystemByName("engine")

	local function completeGame()
		stateMachine:finishGame()
	end
	connections.crashedIntoSun = engine.crashedIntoSun:Connect(completeGame)

	connections.escapedSun = engine.escapedSun:Connect(completeGame)

	spawnToolsAsync()
	tagMap()

	coroutine.wrap(
		function()
			while true do
				local waitTime = METEOR_FREQUENCY_PER_PLAYER / 1 + (#Players:GetPlayers() / 5)

				wait(math.random(waitTime / 1.5, waitTime * 1.5))
				if stateMachine.current ~= "game" then
					return
				end

				local shield = SystemManager.getSystemByName("shield")

				if shield:isOn() and math.random(1, 100) > SHIELD_DEFLECT_RATE then
					sendAlert(Constants.Alert.Success, translate("Shields have deflected a meteor!"))
				else
					spawnMeteor()
				end
			end
		end
	)()
end
