-----------------------


local _lastTeleport = tick()
local _currentQueue = {}

function Queue._addToQueue(player)
	local waitingFor = Conf.min_queue_players - Queue._currentQueueCount()

	-- If this was the last player we were waiting for, start the queue timeout countdown
	if waitingFor == 1 then
		_lastTeleport = tick()
	end

	_currentQueue[player] = tick()

	Queue._sendStatus()
end

function Queue._removeFromQueue(player)
	_currentQueue[player] = nil
	Queue._sendStatus()
end

function Queue._closeQueue()
	local thisQueue = _currentQueue
	_currentQueue = {}
	return thisQueue
end

function Queue._currentQueueCount()
	local count = 0

	for _, _ in pairs(_currentQueue) do
		count = count + 1
	end

	return count
end

function Queue._teleportQueue()
	if Conf.disable_queue then
		-- Don't kick off a game if the queue is not mean tot be enabled
		return
	end

	local destinationId = Queue._destinationId
	local gameMode = Queue._gameMode

	local thisQueue = Queue._closeQueue()
	_lastTeleport = tick()

	Log.Debug.Queue("Reserving for %s", destinationId)

	local token = TeleportService:ReserveServer(destinationId)
	Log.Debug.Queue("Reserved %s for place %s", token, destinationId)

	local playerList = {}
	for player, queueTime in pairs(thisQueue) do
		table.insert(playerList, player)
	end

	local creationData = {
		isolated_server = true,
		game_mode = gameMode,
		player_count = #playerList,
	}

	Log.Debug.Queue("Teleporting %s players to %s (%s)", #playerList, destinationId, gameMode)

	TeleportService:TeleportToPrivateServer(destinationId, token, playerList, nil, creationData)
end

function Queue.setTimeoutState(state)
	if state and not Queue._timeoutEnabled then
		Log.Debug.Queue("Re-enabled timeout.  Restarting countdown")
		_lastTeleport = tick()
	end

	Queue._timeoutEnabled = state

	Log.Debug.Queue("Timeout state: %s", tostring(state))

	Queue._sendStatus()
end

function Queue.teleportQueue()
	Log.Debug.Queue("Progressing.  Buckle up for fun.  *MAXIMUM* fun...")

	Queue._teleportQueue()
end
