--[[
	Stage implementation
]]


local Waiting = {}
Waiting.__index = Waiting

function Waiting.new(gameStageHandler)
	local self = setmetatable({
		gameStageHandler = gameStageHandler,
	}, Waiting)

	return self
end

function Waiting:disableQueueTimeout()
	self._disableQueueTimeout = true
end

function Waiting:startGame(...)
	MatchmakingDestination.startGame(...)
end

function Waiting:initialize()
	-- Spawn every player onto the boat
	for _, player in pairs(Players:GetPlayers()) do
		Util.loadCharacter(player)
	end

	spawn(function()
		DamageHandler.setup()
	end)

	MatchmakingDestination.run(function() self.gameStageHandler:nextStage() end)

	spawn(function()
			while not MatchmakingDestination.isPlaying() do
				if self.gameStageHandler.currentStageClassName ~= "Waiting" or self._disableQueueTimeout then
					return
				end

				local waitTime = tick() - self.gameStageHandler.timeStageStarted

				if waitTime < Conf.queue_time_limit or #Players:getPlayers() < Conf.min_queue_players then
					wait(1)
					self.gameStageHandler._queueWaitTime = waitTime

				else
					MatchmakingDestination.startGame()
					break
				end
			end
	end)
end

function Waiting:destroy()
	-- TODO:  Any teardown for MatchmakingDestination

	-- Reset the character back to the default state
	for _, player in pairs(Players:GetPlayers()) do
		if player.Character then
			-- Remove the force field from the character
			local forceField = player.Character:FindFirstChild("WaitingForceField")
			if forceField then
				forceField:Destroy()
			end

			-- Remove all equipped tools that are not the building tool
			for _, instance in pairs(player.Character:GetChildren()) do
				if instance:IsA("Tool") then
					instance:Destroy()
				end
			end
		end

		-- Remove all tools from the player's backpack that are not the building tool
		for _, instance in pairs(player.Backpack:GetChildren()) do
			if instance:IsA("Tool") then
				instance:Destroy()
			end
		end
	end
end
