-- Leaderboard table

local leaderboard = {}
local _table = false

function leaderboard.new()
	local self = script.Parent:WaitForChild("Table")
	
	function leaderboard.AddRow(player)
		-- Only add row for player if it does not exist
		if self:FindFirstChild(player.Name) then return end

		local row = Instance.new("Frame")
		row.Name = player.Name
		row.Size = UDim2.new(1, 0, 0, 28)
		row.BackgroundColor3 = Color3.new(255/255, 179/255, 71/255)
		row.BorderSizePixel = 0
		row.Parent = self
		
		local column1 = Instance.new("TextLabel")
		column1.Name = "Username"
		column1.Size = UDim2.new(0.6, 0, 0.8, 0)
		column1.Position = UDim2.new(0.05, 0,0.1, 0)
		column1.BackgroundTransparency = 1
		column1.TextColor3 = Color3.new(1, 1, 1)
		column1.TextScaled = true
		column1.TextXAlignment = Enum.TextXAlignment.Left
		column1.TextYAlignment = Enum.TextYAlignment.Center
		column1.Text = player.Name
		column1.Parent = row
		
		local column2 = Instance.new("TextLabel")
		column2.Name = "Points"
		column2.Size = UDim2.new(0.25, 0, 0.8, 0)
		column2.Position = UDim2.new(0.7, 0,0.1, 0)
		column2.BackgroundTransparency = 1
		column2.TextColor3 = Color3.new(1, 1, 1)
		column2.TextScaled = true
		column2.TextXAlignment = Enum.TextXAlignment.Right
		column2.TextYAlignment = Enum.TextYAlignment.Center
		column2.Text = 0
		column2.Parent = row
		
		-- Listen for point value changes and update leaderboard
		local leaderstats = player:WaitForChild("CustomLeaderstats")
		local points = leaderstats:WaitForChild("Points")
		points.Changed:Connect(function()
			column2.Text = points.Value
			column2.LayoutOrder = points.Value
		end)
	end

	function leaderboard.DeleteRow(player)
		local rowToDelete = self:FindFirstChild(player.Name)
		if rowToDelete then
			rowToDelete:Destroy()
			return true
		else
			return false
		end
	end
	
	function leaderboard.Populate()
		local playerList = Players:GetChildren()
		for i, player in pairs (playerList) do
			leaderboard.AddRow(player)				
		end
	end
		
	function leaderboard.Resize(child)
		-- Size of table should be # of children - 2 to account to UIListLayout and this script
		local size = #self:GetChildren() - 2
		self.CanvasSize = UDim2.new(0,0,size,0)
	end
	
	-- Signals
	Players.PlayerAdded:Connect(leaderboard.AddRow)
	Players.PlayerRemoving:Connect(leaderboard.DeleteRow)

	self.ChildAdded:Connect(leaderboard.Resize)
	self.ChildRemoved:Connect(leaderboard.Resize)
	
	return leaderboard
end
