-- Function to save player's data

local function savePlayerData(playerUserId)
	if sessionData[playerUserId] then
		local success,data = pcall(function()
			--NOTE!!! adding this print adds save if remove then save is lost
			print("Money --> before SetAsync ",sessionData[playerUserId]["Money"])
			playerData:SetAsync(playerUserId, sessionData[playerUserId])
			print("Money --> After SetAsync ",sessionData[playerUserId]["Money"])
			wait()
		end)
		if not success then
			warn("Cannot save data for player!-------------------------------------->")
			warn("----------------------savePlayerData----------------------------------------------")
			warn("What is the reason ",data)
		end
	end
end

function PlayerStatManager:getPlayerData(player)
	local playerUserId = "Player_" .. player.UserId
	local succes,data = pcall(function() 
		print("Got player data---------------------->")
		return sessionData[playerUserId]
	end)
	if succes == false then
		warn("ERROR---------PlayerStatManager:getPlayerData----------->")
		print(data)
		return nil
	else
		return data	
	end
	
end 

function PlayerStatManager:getStat(player,statName)
	local succes,data = pcall(function() 
		local playerUserId = "Player_" .. player.UserId
		return sessionData[playerUserId][statName]
	end)
	if succes == false then
		warn("ERROR---------PlayerStatManager:getStat----------->")
		print(data)
		return nil
	else
		return data	
	end
end 

function PlayerStatManager:saveStat(player,statName,value)
	local succes,err = pcall(function() 
		local playerUserId = "Player_" .. player.UserId
		sessionData[playerUserId][statName] = value
	end)
	if succes == false then
		warn("ERROR---------PlayerStatManager:saveStat----------->")
		print(err)
	end
end 

function PlayerStatManager:getStatInTycoonPurchases(player,statName)
	local succes,data = pcall(function() 
		local playerUserId = "Player_" .. player.UserId
		return sessionData[playerUserId]["TycoonPurchases"][statName]
	end)
	if succes == false then
		warn("ERROR---------PlayerStatManager:getTycoonPurchases----------->")
		print(data)
		return nil
	else
		return data	
	end
end 

function PlayerStatManager:setPlayerSessionDataToNil(player)
	if player ~= nil then
		local playerUserId = "Player_" .. player.UserId
		if sessionData[playerUserId] then
			sessionData[playerUserId] = nil
		end
	end
end
