--[[
			// UserData.lua
			// API for all user related data

			// TODO:
				Update all local create calls to use GetLocalUserData() and update
					.Create()
				Remove all friends stuff and move to new module
]]
local CoreGui = game:GetService("CoreGui")
local GuiRoot = CoreGui:FindFirstChild("RobloxGui")
local Modules = GuiRoot:FindFirstChild("Modules")
local Players = game:GetService('Players')
local HttpService = game:GetService('HttpService')
local PlatformService = game:GetService('PlatformService')

local AccountManager = require(Modules:FindFirstChild('AccountManager'))
local Http = require(Modules:FindFirstChild('Http'))
local Utility = require(Modules:FindFirstChild('Utility'))

local AccountLinkingEnabled = Utility.IsFastFlagEnabled("AccountLinkEnabled")

local BaseUrl = Http.BaseUrl

local UserData = {}

local currentUserData = nil

local function getLocalPlayer()
	local plr = Players.LocalPlayer
	if not plr then
		while not plr do
			wait()
			plr = Players.LocalPlayer
		end
	end
	return plr
end

local function setVoteCountAsync()
	local voteResult = Http.GetVoteCountAsync()
	currentUserData["VoteCount"] = voteResult and voteResult['VoteCount'] or 0
end

function UserData:Initialize()
	if currentUserData then
		print("Trying to initialize UserData when we already have valid data.")
	end

	currentUserData = {}

	if UserSettings().GameSettings:InStudioMode() then
		local localPlayer = getLocalPlayer()
		currentUserData["Gamertag"] = "InStudioNoGamertag"
		currentUserData["RbxUid"] = localPlayer.userId
		currentUserData["RobloxName"] = localPlayer.Name
		spawn(function()
			setVoteCountAsync()
		end)
	else
		local userInfo = PlatformService:GetPlatformUserInfo()
		if userInfo then
			currentUserData["Gamertag"] = userInfo["Gamertag"]
			currentUserData["RobloxName"] = userInfo["RobloxUserName"]
			currentUserData["RbxUid"] = userInfo["RobloxUserId"]
		else
			currentUserData["Gamertag"] = Players.LocalPlayer.Name
		end

		spawn(function()
			setVoteCountAsync()
			if AccountLinkingEnabled then
				currentUserData["HasLinkedAccount"] = AccountManager:HasLinkedAccountAsync()
				currentUserData["HasRobloxCredentials"] = AccountManager:HasRobloxCredentialsAsync()
			end
		end)
	end
end

function UserData:GetRbxUserId()
	if not currentUserData then
		print("Error: UserData:GetRbxUserId() - UserData has not been initialized. Don't do that!")
		return nil
	end
	return currentUserData["RbxUid"]
end

function UserData:GetDisplayName()
	if not currentUserData then
		print("Error: UserData:GetDisplayName() - UserData has not been initialized. Don't do that!")
		return nil
	end
	return currentUserData["Gamertag"]
end

function UserData:GetRobloxName()
	if not currentUserData then
		print("Error: UserData:GetRobloxName() - UserData has not been initialized. Don't do that!")
		return nil
	end
	return currentUserData["RobloxName"]
end

function UserData:GetAvatarUrl(width, height)
	-- TODO: Update when Thumbnail manager gets fixed
	if not currentUserData then
		print("Error: UserData:GetAvatarUrl() - UserData has not been initialized. Don't do that!")
		return nil
	end
	return BaseUrl..'Thumbs/Avatar.ashx?userid='..tostring(currentUserData.RbxUid)..
			'&width='..tostring(width)..'&height='..tostring(height)
end

function UserData:GetVoteCount()
	if not currentUserData then
		print("Error: UserData:GetVoteCount() - UserData has not been initialized. Don't do that!")
		return nil
	end
	return currentUserData["VoteCount"]
end

function UserData:IncrementVote()
	currentUserData["VoteCount"] = (currentUserData["VoteCount"] or 0) + 1
end

function UserData:DecrementVote()
	currentUserData["VoteCount"] = math.max((currentUserData["VoteCount"] or 0) - 1, 0)
end

function UserData:HasLinkedAccount()
	return currentUserData["HasLinkedAccount"] == true
end

function UserData:HasRobloxCredentials()
	return currentUserData["HasRobloxCredentials"] == true
end

function UserData:SetHasRobloxCredentials(value)
	currentUserData["HasRobloxCredentials"] = value
end

function UserData:Reset()
	currentUserData = nil
end

--[[ This should no longer be used ]]--
function UserData.GetLocalUserIdAsync()
	return UserData.GetLocalPlayerAsync().userId
end

function UserData.GetLocalPlayerAsync()
	local localPlayer = Players.LocalPlayer
	while not localPlayer do
		wait()
		localPlayer = Players.LocalPlayer
	end
	return localPlayer
end

function UserData.GetPlatformUserBalanceAsync()
	local result = Http.GetPlatformUserBalanceAsync()
	if not result then
		-- TODO: Error Code
		return nil
	end
	--

	return result["Robux"]
end

function UserData.GetTotalUserBalanceAsync()
	local result = Http.GetTotalUserBalanceAsync()
	if not result then
		return nil
	end

	return result["robux"]
end

return UserData
