--[[
			// SortData.lua
			// API for Game Sorts
]]
local CoreGui = Game:GetService("CoreGui")
local GuiRoot = CoreGui:FindFirstChild("RobloxGui")
local Modules = GuiRoot:FindFirstChild("Modules")

local Http = require(Modules:FindFirstChild('Http'))
local Strings = require(Modules:FindFirstChild('LocalizedStrings'))

local SortData = {}

local function initPage(data)
	local page = {}

	page.Data = data
	page.Count = #data

	function page:GetPagePlaceIds()
		local ids = {}

		for i = 1, #data do
			ids[i] = data[i]["PlaceID"]
		end

		return ids
	end

	function page:GetPagePlaceNames()
		local names = {}

		for i = 1, #data do
			names[i] = data[i]["Name"]
		end

		return names
	end

	function page:GetCreatorNames()
		local names = {}

		for i = 1, #data do
			names[i] = data[i]["CreatorName"]
		end

		return names
	end

	function page:GetPageIconIds()
		local iconIds = {}

		for i = 1, #data do
			local id = data[i]["ImageId"]
			iconIds[i] = id
		end

		return iconIds
	end

	function page:GetPageVoteData()
		local voteData = {}

		for i = 1, #data do
			local vote = {
				UpVotes = data[i]["TotalUpVotes"];
				DownVotes = data[i]["TotalDownVotes"];
			}
			voteData[i] = vote
		end

		return voteData
	end

	return page
end

-- returns class style table for sorts
function SortData.GetSortCategoriesAsync()
	local result = Http.GetGameSortsAsync()
	if not result then
		-- TODO: Error codes
		return
	end
	--
	local sorts = {}

	for i = 1, #result do
		local sort = {
			Id = result[i]["Id"];
			Name = result[i]["Name"];
		}
		table.insert(sorts, sort)
	end
	table.insert(sorts, { Id = "MyFavorite", Name = Strings:LocalizedString("FavoritesSortTitle") } )
	table.insert(sorts, { Id = "MyRecent", Name = Strings:LocalizedString("RecentlyPlayedSortTitle") } )

	return sorts
end

-- Returns class style table for a game sort, must call GetNextPageAsync to get the first page
function SortData.GetSort(sortId, isSearch)
	local currentIndex = 0
	--
	local sort = {}
	local searchAllGames = sortId == 'MyFavorite' or sortId == 'MyRecent'
	local httpFunc = isSearch and Http.SearchGamesAsync or Http.GetGamesFromSortAsync

	function sort:GetCurrentPageAsync(pageSize)
		local result = httpFunc(sortId, currentIndex, pageSize, searchAllGames)
		if not result then
			print("SortData.GetSort() failed to get result from web.")
			return nil
		end

		return initPage(result)
	end

	function sort:AdvanceToNextPageAsync(pageSize)
		currentIndex = currentIndex + pageSize
		local result = httpFunc(sortId, currentIndex, pageSize, searchAllGames)
		if not result then
			print("sortData - AdvanceTonextPageAsync failed to get result from web.")
			return nil
		end

		return initPage(result)
	end

	return sort
end

function SortData.GetSearchGames(keyword)
	return SortData.GetSort(keyword, true)
end

return SortData
