--Save data to DataStore

local function savePlayerData(player, playerLeaving)
	local pdata = main.pd[player]
	if pdata and (pdata.DataToUpdate or playerLeaving) then
		return main:GetModule("DataStores"):DataStoreRetry(datastoreRetries, function()
			return playerDataStore:UpdateAsync(player.UserId, function(oldValue)
				local newValue = oldValue or {DataKey = 0}
				if pdata and main.pd[player] then
					if pdata.DataKey == newValue.DataKey then
						main.pd[player].DataToUpdate = false
						main.pd[player].DataKey = pdata.DataKey + 1
						--
						local pdataToSave = {}
						for a,b in pairs(main.pd[player]) do
							pdataToSave[a] = b
						end
						if not pdataToSave.SaveRank then
						--if playerLeaving and not pdataToSave.SaveRank then
							pdataToSave.Rank = 0
						end
						local dataNotToSave = dataNotToSave()
						for i, v in pairs(dataNotToSave) do
							pdataToSave[v] = nil
						end
						--
						newValue = pdataToSave
					else
						newValue = nil --Prevent data being overwritten
					end
				end
				return newValue
			end)
		end)
	end
end


