--[[
	ETC
]]

local random = Random.new()
local EventData = ReplicatedStorage.Events.EventData
EventData.OnServerEvent:Connect(function(player, cmd, ...)
	if cmd == "SpectatePlayer" then
		local playerToSpectate = ...
		if not Util.playerIsAlive(player) and Util.playerIsAlive(playerToSpectate) then
			player.ReplicationFocus = playerToSpectate.Character.Head
		end
	end
end)

local RespawnEvent = ReplicatedStorage.Events.RespawnEvent
RespawnEvent.Event:Connect(function(player)
	if gameStageHandler.currentStageClassName == "Gameplay" and player and player.Character then
		wait(Conf.respawnTime)
		if not Util.playerIsAlive(player) then
			-- Save all player's weapon names to give them new instances of them when they respawn
			local toolNamesBeforeDeath = {}
			for _, instance in pairs(player.Backpack:GetChildren()) do
				if instance:IsA("Tool") and ReplicatedStorage.Assets.Weapons:FindFirstChild(instance.Name) then
					table.insert(toolNamesBeforeDeath, instance.Name)
				end
			end

			local characterAddedConn = nil
			characterAddedConn = player.CharacterAdded:Connect(function(character)
				characterAddedConn:Disconnect()

				-- Wait a frame for the character to initialize/spawn
				RunService.Heartbeat:Wait()

				-- Add weapons the player had before dying to their backpack
				for _, weaponName in ipairs(toolNamesBeforeDeath) do
					local weaponTemplate = ReplicatedStorage.Assets.Weapons:FindFirstChild(weaponName)
					if weaponTemplate ~= nil then
						weaponTemplate:Clone().Parent = player.Backpack
					end
				end

				-- Set up the player's character when they respawn
				local head = character:WaitForChild("Head")
				-- Calculate where to spawn player based on storm's current target position/radius
				local targetPos, targetRadius = ShrinkingBarrier.getNextPositionAndRadius()
				local randomRadius = targetRadius * random:NextNumber(Conf.respawn_radius_lowest_fraction, Conf.respawn_radius_highest_fraction)
				local randomRadians = random:NextNumber(0, 2 * math.pi)
				if Conf.num_teams == 2 then
					-- In team mode, make players spawn only on their team's half of the map
					local dividingAngle = ShrinkingBarrier.getDividingAngle()
					if PlayerMatchInfo.GetField(player, "teamNumber") == 1 then
						randomRadians = random:NextNumber(dividingAngle - math.pi, dividingAngle)
					else
						randomRadians = random:NextNumber(dividingAngle, dividingAngle + math.pi)
					end
				end
				local xSpawn = targetPos.X + randomRadius * math.cos(randomRadians)
				local ySpawn = targetPos.Y + Conf.respawn_height_fraction * Conf.delivery_vehicle_spawn_height
				local zSpawn = targetPos.Z + randomRadius * math.sin(randomRadians)
				head.CFrame = CFrame.new(xSpawn, ySpawn, zSpawn)
				player.ReplicationFocus = head
			end)
			Util.loadCharacter(player)
		end
	end
end)

if not PingHandler.doingSetup and not PingHandler.didSetup then
	PingHandler.setup()
end
