--Save data to DataStore

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


