--[[
	Stage implementation
]]


local Gameplay = {}
Gameplay.__index = Gameplay

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

	return self
end

function Gameplay:initialize()
	-- Start systems
	ServerTime.run()

	-- Pass shrinking barrier the dividing angle if there are teams
	local randomGenerator = Random.new()
	local directionAngle = randomGenerator:NextNumber(0, math.pi * 2)
	ShrinkingBarrier.run(directionAngle)

	-- Spawn delivery vehicle (or multiple if there are teams)
	local stormPos, stormRadius = ShrinkingBarrier.getTargetPositionAndRadius()
	if Conf.num_teams == 0 then
		local deliveryVehicle = DeliveryVehicle.new()
		deliveryVehicle:spawn(stormPos, stormRadius, directionAngle, 0)
		deliveryVehicle:beginDelivery()
	else
		for i = 1, Conf.num_teams do
			local deliveryVehicle = DeliveryVehicle.new()
			deliveryVehicle:spawn(stormPos, stormRadius, directionAngle, i)
			deliveryVehicle:beginDelivery()
		end
	end
	
	-- Setup character
	for _, player in pairs(Players:GetPlayers()) do
		if player.Character then
			self:setupCharacter(player, player.Character)
		end
	end
end

function Gameplay:destroy()
	self.playerCharacters = nil
end

function Gameplay:characterAdded(player, character)
	self:setupCharacter(player, character)
end

function Gameplay:playerAdded(player)
	local warningMessage = "Player " .. player.Name .. " joined after game start"
	warn(warningMessage)
	WarningEvent:FireAllClients(warningMessage)
end

function Gameplay:setupCharacter(player, character)
	if Conf.player_nil_parent_enabled then
		-- Unparent the player character, but keep a reference so they don't get thrown away
		self.playerCharacters[player] = player.Character
		player.Character.Parent = nil
	elseif not PlayerMatchInfo.GetField(player, "didJump") then
		-- Give the player the Pistol as the default starting weapon
		ReplicatedStorage.Assets.Weapons.Pistol:Clone().Parent = player.Backpack

		-- Grant the player a force field so they cant be killed in the waiting area
		local forceField = Instance.new("ForceField")
		forceField.Name = "WaitingToJumpForceField"
		forceField.Visible = false
		forceField.Parent = character
	end
end

return Gameplay
