-- << SET UP PLAYER DATA >>

local getLimitPerMin = 6
local getRefreshInterval = 10
local getLimit = getLimitPerMin*(getRefreshInterval/60)
local getRequests = {}
spawn(function()
	while true do
		wait(getRefreshInterval)
		getRequests = {}
	end
end)
function module:GetData(caller, retries, userId)
	if not getRequests[caller] then
		getRequests[caller] = 0
	end
	getRequests[caller] = getRequests[caller] + 1
	if getRequests[caller] <= getLimit then
		local success, data = main:GetModule("DataStores"):GetData(playerDataStore, retries, userId)
		return success, data
	else
		--warn(caller.Name,"exeeded getLimit!")
	end
end


function module:SetupPlayerData(player)
	
	local dataTemplate = getDataTemplate()
	local success, pdata = self:GetData(player, datastoreRetries, player.UserId)
	
	--Can't access DataStore
	if not success and not main.isStudio then
		return nil
	
	--New player
	elseif not pdata then
		pdata = dataTemplate
		savePlayerData(player)
		local welcomeBadgeId = tonumber(main.settings.WelcomeBadgeId)
		if welcomeBadgeId and welcomeBadgeId > 0 then
			main.badgeService:AwardBadge(player.UserId, welcomeBadgeId)
		end
	
	--Existing player
	else
		for statName, statValue in pairs(dataTemplate) do
			if pdata[statName] == nil then
				pdata[statName] = statValue
			end
			if statName == "DefaultSettings" then
				for i, settingName in pairs(defaultSettingsToAdd) do
					if pdata[statName][settingName] == nil then
						pdata[statName][settingName] = settings[settingName]
					end
				end
			end
		end
		
	end
	
	main.pd[player] = pdata
	return pdata
end
 