-- Process Tiles

local ZoneParser = require(script.ZoneParser)
local PlayerManager = require(script.PlayerManager)

ZoneParser:ParseType("Straight")
ZoneParser:ParseType("Left")
ZoneParser:ParseType("Right")
ZoneParser:ParseType("TJunction")
ZoneParser:ParseType("Obstacle")

ZoneParser:ParseType("Tutorial")

game.Workspace.DisplayElements:Destroy()

local trackSlots = {}
for i = 1, 6 do
	trackSlots[i] = {player = nil, height = 50 * i}
end

local managers = {}

game.ReplicatedStorage.Events.StartRunning.OnServerEvent:connect(function(player)
	
	local playerSlot = player:WaitForChild("slotHeight")
	local manager = PlayerManager:Run(player, playerSlot.Value)
	managers[player.Name] = manager
	
	wait()
	
	player:LoadCharacter()
end)

game.Players.PlayerAdded:connect(function(player)
	local playerSlot = nil
	for i = 1, 6 do
		local slot = trackSlots[i]
		if not slot.player then
			slot.player = player
			playerSlot = slot
			break
		end
	end
	local slotHeight = Instance.new("IntValue", player)
	slotHeight.Name = "slotHeight"
	slotHeight.Value = playerSlot.height
end)

game.Players.PlayerRemoving:connect(function(player)
	if managers[player.Name] then
		managers[player.Name].Cleanup()
		managers[player.Name] = nil
	end
end)
