-- Copyright ROBLOX 2015
--[[
		Filename: GamePane.lua
		Written By: Kyler Mulherin, Jason Roth

		TODO:
			Make responsive
]]

local CoreGui = Game:GetService("CoreGui")
local GuiRoot = CoreGui:FindFirstChild("RobloxGui")
local Modules = GuiRoot:FindFirstChild("Modules")

local Utility = require(Modules:FindFirstChild('Utility'))
local GlobalSettings = require(Modules:FindFirstChild('GlobalSettings'))
local GuiService = game:GetService('GuiService')

local GameSort = require(Modules:FindFirstChild('GameSort'))
local SortData = require(Modules:FindFirstChild('SortData'))
local ScrollingGrid = require(Modules:FindFirstChild('ScrollingGrid'))
local EventHub = require(Modules:FindFirstChild('EventHub'))
local ScreenManager = require(Modules:FindFirstChild('ScreenManager'))
local Strings = require(Modules:FindFirstChild('LocalizedStrings'))
local LoadingWidget = require(Modules:FindFirstChild('LoadingWidget'))

--CONSTANTS
local SPACING = 33

local function CreateGamePane(parent)
	local this = {}

	local sortCatagories = nil
	local defaultSelection = nil
	local imageSize = UDim2.new(0, 298, 0, 298)
	local spacing = Vector2.new(14, 14)
	local rows, columns = 2, 2

	local inFocus = false

	local noSelectionObject = Utility.Create'ImageLabel'
	{
		BackgroundTransparency = 1;
	}

	-- UI Elements
	local GamePaneContainer = Utility.Create'Frame'
	{
		Name = 'GamePane';
		Size = UDim2.new(1, 0, 1, 0);
		BackgroundTransparency = 1;
		Parent = parent;
		SelectionImageObject = noSelectionObject;
		Visible = false;
	}
	defaultSelection = GamePaneContainer

	local gameSortsPane  = ScrollingGrid()
	gameSortsPane:SetPosition( UDim2.new(0, 0, 0, 0))
	gameSortsPane:SetCellSize(Vector2.new(610, 646))
	gameSortsPane:SetSize(UDim2.new(1, GlobalSettings.TitleSafeInset.X.Offset, 1, 0))
	gameSortsPane:SetScrollDirection(gameSortsPane.Enum.ScrollDirection.Horizontal)
	gameSortsPane:SetParent(GamePaneContainer)
	gameSortsPane:SetClipping(false)
	gameSortsPane:SetSpacing(Vector2.new(SPACING, SPACING))
	gameSortsPane.Container.Visible = false

	local function setSelectionOnLoad()
		-- TODO: Update when we figure out better top level nav
		local currentSelection = GuiService.SelectedCoreObject
		if currentSelection and currentSelection == GamePaneContainer then
			GuiService.SelectedCoreObject = defaultSelection
		end
	end

	local setSortsDebounce = false
	local function setSortView()
		if setSortsDebounce then return end
		setSortsDebounce = true
		if not sortCatagories then
			spawn(function()
				sortCatagories = SortData.GetSortCategoriesAsync()
			end)
		end

		local views = {}

		local function loadSortsAsync()
			while not sortCatagories do
				wait()
			end

			for i = 1, #sortCatagories do
				local sort = sortCatagories[i]
				--
				local sortData = SortData.GetSort(sort["Id"], false)
				if sortData then
					local sortPage = sortData:GetCurrentPageAsync(4)
					if sortPage and sortPage.Count > 0 then
						local view = GameSort:CreateGridView(UDim2.new(), imageSize, spacing, rows, columns)
						table.insert(views, view)
						local iconIds = sortPage:GetPageIconIds()
						local names = sortPage:GetPagePlaceNames()
						local placeIds = sortPage:GetPagePlaceIds()
						view:SetImages(iconIds)
						view:ConnectInput(placeIds, names, iconIds, sort["Name"], sort["Id"])
						view:SetTitle(sort["Name"])
					end
				end
			end
		end
		local loader = LoadingWidget(
			{ Parent = GamePaneContainer }, { loadSortsAsync })
		spawn(function()
			loader:AwaitFinished()
			loader:Cleanup()
			loader = nil
			if GamePaneContainer.Visible then
				for i = 1, #views do
					gameSortsPane:AddItem(views[i]:GetContainer())
					if defaultSelection == GamePaneContainer then
						defaultSelection = views[i]:GetDefaultSelection()
					end
				end
				gameSortsPane.Container.Visible = true
				setSelectionOnLoad()
				this.TransitionTweens = ScreenManager:DefaultFadeIn(gameSortsPane.Container)
				ScreenManager:PlayDefaultOpenSound()
			end
			setSortsDebounce = false
		end)
	end

	-- SCREEN FUNCTIONS
	function this:SetPosition(newPosition)
		GamePaneContainer.Position = newPosition
	end
	function this:SetParent(newParent)
		GamePaneContainer.Parent = newParent
	end

	function this:IsAncestorOf(object)
		return GamePaneContainer and GamePaneContainer:IsAncestorOf(object)
	end

	function this:GetName()
		return Strings:LocalizedString('GameWord')
	end

	function this:IsFocused()
		return inFocus
	end

	function this:Show()
		ScreenManager:DefaultCancelFade(self.TransitionTweens)
		setSortView()
		GamePaneContainer.Visible = true
	end
	function this:Hide()
		GamePaneContainer.Visible = false
		gameSortsPane.Container.Visible = false

		ScreenManager:DefaultCancelFade(self.TransitionTweens)
		self.TransitionTweens = nil
	end
	function this:Focus()
		inFocus = true
		GuiService.SelectedCoreObject = defaultSelection
	end
	function this:RemoveFocus()
		inFocus = false
		local selectedObject = GuiService.SelectedCoreObject
		if selectedObject and selectedObject:IsDescendantOf(GamePaneContainer) then
			GuiService.SelectedCoreObject = nil
		end
		defaultSelection = GamePaneContainer
		gameSortsPane:RemoveAllItems()
	end

	--[[ Initialize - Don't Block ]]--
	spawn(function()
		sortCatagories = SortData.GetSortCategoriesAsync()
	end)

	return this
end

return CreateGamePane
