--[[
			// SignInScreen.lua
]]
local CoreGui = Game:GetService("CoreGui")
local GuiRoot = CoreGui:FindFirstChild("RobloxGui")
local Modules = GuiRoot:FindFirstChild("Modules")

local GuiService = game:GetService('GuiService')
local PlatformService = game:GetService('PlatformService')
local UserInputService = game:GetService('UserInputService')

local AccountManager = require(Modules:FindFirstChild('AccountManager'))
local AssetManager = require(Modules:FindFirstChild('AssetManager'))
local Errors = require(Modules:FindFirstChild('Errors'))
local ErrorOverlay = require(Modules:FindFirstChild('ErrorOverlay'))
local EventHub = require(Modules:FindFirstChild('EventHub'))
local GlobalSettings = require(Modules:FindFirstChild('GlobalSettings'))
local LoadingWidget = require(Modules:FindFirstChild('LoadingWidget'))
local ScreenManager = require(Modules:FindFirstChild('ScreenManager'))
local SoundManager = require(Modules:FindFirstChild('SoundManager'))
local Strings = require(Modules:FindFirstChild('LocalizedStrings'))
local Utility = require(Modules:FindFirstChild('Utility'))

local LinkAccountScreen = require(Modules:FindFirstChild('LinkAccountScreen'))

local function createSignInScreen()
	local this = {}

	local isFocused = false

	local DefaultButtonColor = GlobalSettings.GreyButtonColor
	local SelectedButtonColor = GlobalSettings.GreySelectedButtonColor
	local DefaultButtonTextColor = GlobalSettings.WhiteTextColor
	local SelectedButtonTextColor = GlobalSettings.TextSelectedColor

	local gamerTagStr = ""
	local userInfo = nil
	if UserSettings().GameSettings:InStudioMode() then
		userInfo = {
			Gamertag = game.Players.LocalPlayer.Name
		}
	elseif PlatformService and UserInputService:GetPlatform() == Enum.Platform.XBoxOne then
		userInfo = PlatformService:GetPlatformUserInfo()
	end
	if userInfo then
		local gamerTag = userInfo["Gamertag"]
		if gamerTag then
			gamerTagStr = string.format(Strings:LocalizedString("PlayAsPhrase"), gamerTag)
		end
	end

	local ModalOverlay = Utility.Create'Frame'
	{
		Name = "ModalOverlay";
		Size = UDim2.new(1, 0, 1, 0);
		BackgroundTransparency = GlobalSettings.ModalBackgroundTransparency;
		BackgroundColor3 = GlobalSettings.ModalBackgroundColor;
		BorderSizePixel = 0;
		ZIndex = 4;
	}

	local Container = Utility.Create'Frame'
	{
		Name = "SignInScreen";
		Size = UDim2.new(1, 0, 1, 0);
		BackgroundTransparency = 1;
		Visible = false;
	}
	local RobloxLogo = Utility.Create'ImageLabel'
	{
		Name = "RobloxLogo";
		BackgroundTransparency = 1;
		Parent = Container;
	}
	AssetManager.LocalImage(RobloxLogo,
		'rbxasset://textures/ui/Shell/Icons/ROBLOXLogoStart', {['720'] = UDim2.new(0,324,0,86); ['1080'] = UDim2.new(0,487,0,129);})
	Utility.CalculateAnchor(RobloxLogo, UDim2.new(0.5,0,0.5,0), Utility.Enum.Anchor.Center)

	local FadeInFrame = Utility.Create'Frame'
	{
		Name = "FadeInFrame";
		Size = UDim2.new(1, 0, 1, 0);
		BackgroundTransparency = 1;
		Visible = false;
		Parent = Container;
	}

	local HintText = Utility.Create'TextLabel'
	{
		Name = "HintText";
		Size = UDim2.new(0, 1044, 0, 95);
		BackgroundTransparency = 1;
		Font = GlobalSettings.RegularFont;
		FontSize = GlobalSettings.TitleSize;
		TextColor3 = GlobalSettings.WhiteTextColor;
		TextWrapped = true;
		Text = Strings:LocalizedString("NewUserPhrase");
		Parent = FadeInFrame;
	}
	Utility.CalculateAnchor(HintText, UDim2.new(0.5,0,0.5,0), Utility.Enum.Anchor.Center)

	local SignInButton = Utility.Create'ImageButton'
	{
		Name = "SignInButton";
		Size = UDim2.new(0, 200, 0, 64);
		Position = UDim2.new(0.5, -100, 1, -64 - 170);
		BackgroundTransparency = 1;
		ImageColor3 = DefaultButtonColor;
		Image = 'rbxasset://textures/ui/Shell/Buttons/Generic9ScaleButton@720.png';
		ScaleType = Enum.ScaleType.Slice;
		SliceCenter = Rect.new(Vector2.new(4, 4), Vector2.new(28, 28));
		ZIndex = 2;
		Parent = FadeInFrame;

		SoundManager:CreateSound('MoveSelection');
		AssetManager.CreateShadow(1)
	}

	local PlayAsButton = SignInButton:Clone()
	PlayAsButton.Name = "PlayAsButton"
	PlayAsButton.Size = UDim2.new(0, 360, 0, 64);
	PlayAsButton.Position = UDim2.new(0.5, -180, 1, SignInButton.Position.Y.Offset - 64 - 44)
	PlayAsButton.Parent = FadeInFrame

	local SignInText = Utility.Create'TextLabel'
	{
		Name = "SignInText";
		Size = UDim2.new(1, 0, 1, 0);
		BackgroundTransparency = 1;
		Font = GlobalSettings.RegularFont;
		FontSize = GlobalSettings.ButtonSize;
		TextColor3 = DefaultButtonTextColor;
		Text = string.upper(Strings:LocalizedString("SignInPhrase"));
		ZIndex = 2;
		Parent = SignInButton;
	}
	local PlayAsText = SignInText:Clone()
	PlayAsText.Text = string.upper(gamerTagStr)
	PlayAsText.Parent = PlayAsButton

	PlayAsButton.SelectionGained:connect(function()
		PlayAsButton.ImageColor3 = SelectedButtonColor
		PlayAsText.TextColor3 = SelectedButtonTextColor
	end)
	PlayAsButton.SelectionLost:connect(function()
		PlayAsButton.ImageColor3 = DefaultButtonColor
		PlayAsText.TextColor3 = DefaultButtonTextColor
	end)
	SignInButton.SelectionGained:connect(function()
		SignInButton.ImageColor3 = SelectedButtonColor
		SignInText.TextColor3 = SelectedButtonTextColor
	end)
	SignInButton.SelectionLost:connect(function()
		SignInButton.ImageColor3 = DefaultButtonColor
		SignInText.TextColor3 = DefaultButtonTextColor
	end)

	local function animateOnShow()
		Utility.TweenPositionOrSet(RobloxLogo,
			UDim2.new(0.5, RobloxLogo.Position.X.Offset, 0.5, RobloxLogo.Position.Y.Offset - 136), Enum.EasingDirection.InOut,
			Enum.EasingStyle.Quad, 0.5, false, function()
				FadeInFrame.Visible = true
				if isFocused then
					GuiService.SelectedCoreObject = PlayAsButton
				end
			end)
	end

	local function PlayAsAsync()
		local signInResult = nil
		local loader = LoadingWidget(
			{ Parent = Container }, {
			function()
				-- TODO: Get users gamepad
				signInResult = AccountManager:SignInAsync(Enum.UserInputType.Gamepad1)
			end
		})
		-- set up full screen loader
		ModalOverlay.Parent = GuiRoot
		local selectedObject = GuiService.SelectedCoreObject
		GuiService.SelectedCoreObject = nil

		-- call loader
		loader:AwaitFinished()

		-- clean up
		loader:Cleanup()
		loader = nil
		GuiService.SelectedCoreObject = selectedObject
		ModalOverlay.Parent = nil

		if signInResult == AccountManager.AuthResults.Success then
			ScreenManager:CloseCurrent()
			EventHub:dispatchEvent(EventHub.Notifications["AuthenticationSuccess"])
		else
			local err = signInResult and Errors.Authentication[signInResult] or Errors.Default
			ScreenManager:OpenScreen(ErrorOverlay(err), false)
		end
	end

	--[[ Input ]]--
	local isSigningIn = false
	PlayAsButton.MouseButton1Click:connect(function()
		if isSigningIn then return end
		isSigningIn = true
		SoundManager:Play('ButtonPress')
		PlayAsAsync()
		isSigningIn = false
	end)

	SignInButton.MouseButton1Click:connect(function()
		SoundManager:Play('ButtonPress')
		local linkAccountScreen = LinkAccountScreen()
		linkAccountScreen:SetParent(Container.Parent)
		ScreenManager:OpenScreen(linkAccountScreen, true)
	end)

	--[[ Public API ]]--
	function this:SetParent(newParent)
		Container.Parent = newParent
	end
	function this:Show()
		Utility.CalculateAnchor(RobloxLogo, UDim2.new(0.5,0,0.5,0), Utility.Enum.Anchor.Center)
		Container.Visible = true
		animateOnShow()
	end
	function this:Hide()
		Container.Visible = false
		FadeInFrame.Visible = false
	end
	function this:Focus()
		isFocused = true
		GuiService:AddSelectionParent("SignInScreen", FadeInFrame)
		GuiService.SelectedCoreObject = PlayAsButton
	end
	function this:RemoveFocus()
		isFocused = false
		GuiService:RemoveSelectionGroup("SignInScreen")
		GuiService.SelectedCoreObject = nil
	end

	return this
end

return createSignInScreen
