-- << SERVER RANKS >>

function module:CreateServerRanks()
	coroutine.wrap(function()
	
		local serverRankInfo = main.signals.RetrieveServerRanks:InvokeServer()
		
		--Organise ranks
		local rankPositions = {}
		local ranks = {}
		local plrRanks = {}
		for i, rankDetails in pairs(main.settings.Ranks) do
			local rankId = rankDetails[1]
			local rankName = rankDetails[2]
			table.insert(ranks, 1, {rankId, rankName, {}})
		end
		for i,v in pairs(ranks) do
			rankPositions[v[1]] = i
		end
		
		--Split players into ranks
		for i, playerRankInfo in pairs(serverRankInfo) do
			local plr = playerRankInfo.Player
			local rankId = playerRankInfo.RankId
			local rankTypeId = playerRankInfo.RankType
			local rankDetail = ranks[rankPositions[rankId]]
			if rankDetail then
				table.insert(rankDetail[3], {plr, rankTypeId})
			end
		end
	
		--Sort ranks by RankType (Perm > Server > Temp)
		for i, rankInfo in pairs(ranks) do
			local listOfPlrs = rankInfo[3]
			table.sort(listOfPlrs, function(a,b) return a[2] < b[2] end)
		end
		
		--Clear labels
		main:GetModule("cf"):ClearPage(pages.serverRanks)
		
		--Setup labels
		local rankTypesReversed = {}
		for a,b in pairs(main.rankTypes) do
			rankTypesReversed[b] = a
		end
		local labelCount = 0
		for i, rankInfo in pairs(ranks) do
			local rankId = rankInfo[1]
			local rankName = rankInfo[2]
			local listOfPlrs = rankInfo[3]
			for _, playerRankDetail in pairs(listOfPlrs) do
				labelCount = labelCount + 1
				local plr = playerRankDetail[1]
				local rankTypeId = playerRankDetail[2]
				local rankTypeName = rankTypesReversed[rankTypeId]
				local label = templates.admin:Clone()
				label.Name = "Label".. labelCount
				label.PlrName.Text = plr.Name
				label.PlrRank.Text = rankName.." ("..rankTypeName..")"
				label.PlayerImage.Image = main:GetModule("cf"):GetUserImage(plr.UserId)
				label.BackgroundColor3 = main:GetModule("cf"):GetLabelBackgroundColor(labelCount)
				label.Visible = true
				label.Parent = pages.serverRanks
			end
		end
		
		--Canvas Size
		pages.serverRanks.CanvasSize = UDim2.new(0, 0, 0, labelCount*templates.admin.AbsoluteSize.Y)
		
	end)()
end


