local function q(q)local R=main.sd[q]return(main:GetModule("\068\097\116\097\083\116\111\114\101\115")):DataStoreRetry(datastoreRetries,function()return systemDataStore:UpdateAsync(q,function(Y)local h=Y or dataTemplate(q)if R then if R.DataKey==h.DataKey then h.DataToUpdate=false h.DataKey=h.DataKey+1 for q,R in pairs(R)do if q=="\082\101\099\111\114\100\115\084\111\065\100\100"and#R>0 then for q,R in pairs(R)do table.insert(h.Records,R)end elseif(q=="\082\101\099\111\114\100\115\084\111\082\101\109\111\118\101"or q=="\082\101\099\111\114\100\115\084\111\077\111\100\105\102\121")and#R>0 then for R,Y in pairs(R)do local X=(main:GetModule("\099\102")):FindUserIdInRecord(h.Records,Y.UserId)if X then table.remove(h.Records,X)if q=="\082\101\099\111\114\100\115\084\111\077\111\100\105\102\121"then table.insert(h.Records,Y)else end end end elseif q~="\082\101\099\111\114\100\115"and(q~="\068\097\116\097\075\101\121"and q~="\068\097\116\097\084\111\085\112\100\097\116\101")then h[q]=R end end main.sd[q]=h else h=nil end end return h end)end)end

local function saveSystemData(key)
	local sdata = main.sd[key]
	return main:GetModule("DataStores"):DataStoreRetry(datastoreRetries, function()
		return systemDataStore:UpdateAsync(key, function(oldValue)
			local newValue = oldValue or dataTemplate(key)
			if sdata then
				if sdata.DataKey == newValue.DataKey then
					newValue.DataToUpdate = false
					newValue.DataKey = newValue.DataKey + 1
					for statName, statValue in pairs(sdata) do
						if statName == "RecordsToAdd" and #statValue > 0 then
							for i,record in pairs(statValue) do
								--print("Datastore: "..key.." | AddRecord | "..record.UserId)
								table.insert(newValue.Records, record)
							end
						elseif (statName == "RecordsToRemove" or statName == "RecordsToModify") and #statValue > 0 then
							for i,record in pairs(statValue) do
								local recordToRemovePos = main:GetModule("cf"):FindUserIdInRecord(newValue.Records, record.UserId)
								if recordToRemovePos then
									table.remove(newValue.Records, recordToRemovePos)
									if statName == "RecordsToModify" then
										--print("Datastore: "..key.." | ModifyRecord | "..record.UserId)
										table.insert(newValue.Records, record)
									else
										--print("Datastore: "..key.." | RemoveRecord | "..record.UserId)
									end
								end
							end
						elseif statName ~= "Records" and statName ~= "DataKey" and statName ~= "DataToUpdate" then
							newValue[statName] = statValue
						end
					end
					main.sd[key] = newValue
				else
					newValue = nil
				end
			end
			return newValue
		end)
	end)
end


