function DataStore2.Combine(I,...)for q,H in ipairs({...})do combinedDataStoreInfo[H]=I end end function DataStore2.ClearCache()DataStoreCache={}end function DataStore2.SaveAll(I)if DataStoreCache[I]then for I,q in pairs(DataStoreCache[I])do if q.combinedStore==nil then q:Save()end end end end DataStore2.SaveAllAsync=Promise.promisify(DataStore2.SaveAll)function DataStore2.PatchGlobalSettings(I)for I,q in pairs(I)do assert(Settings[I]~=nil,"\078\111 \115\117\099\104 \107\101\121 \101\120\105\115\116\115\058 "..I)Settings[I]=q end end function DataStore2.__call(I,q,H)assert(typeof(q)=="\115\116\114\105\110\103"and IsPlayer.Check(H),("\068\097\116\097\083\116\111\114\101\050\040\041 \065\080\073 \099\097\108\108 \101\120\112\101\099\116\101\100 \123\115\116\114\105\110\103 \100\097\116\097\083\116\111\114\101\078\097\109\101\044 \080\108\097\121\101\114 \112\108\097\121\101\114\125\044 \103\111\116 \123\037\115\044 \037\115\125"):format(typeof(q),typeof(H)))if DataStoreCache[H]and DataStoreCache[H][q]then return DataStoreCache[H][q]elseif combinedDataStoreInfo[q]then local I=DataStore2(combinedDataStoreInfo[q],H)I:BeforeSave(function(I)for q in pairs(I)do if combinedDataStoreInfo[q]then local B=DataStore2(q,H)local A=B:Get(nil,true)if A~=nil then if B.combinedBeforeSave then A=B.combinedBeforeSave(clone(A))end I[q]=A end end end return I end)local B=setmetatable({combinedName=q,combinedStore=I},{__index=function(q,H)return CombinedDataStore[H]or I[H]end})if not DataStoreCache[H]then DataStoreCache[H]={}end DataStoreCache[H][q]=B return B end local B={Name=q;UserId=H.UserId;callbacks={},beforeInitialGet={},afterSave={},bindToClose={}}B.savingMethod=SavingMethods[Settings.SavingMethod].new(B)setmetatable(B,DataStoreMetatable)local A,i=Instance.new("\066\105\110\100\097\098\108\101\069\118\101\110\116"),false local w=Instance.new("\066\105\110\100\097\098\108\101\069\118\101\110\116")local O=function()if not i then Promise.defer(function()w:Fire()end)A.Event:Wait()end local I=B:Get(nil,true)for q,B in ipairs(B.bindToClose)do B(H,I)end end local e,g=pcall(function()game:BindToClose(function()if O==nil then return end O()end)end)if not e then warn("\068\097\116\097\083\116\111\114\101\050 \099\111\117\108\100 \110\111\116 \066\105\110\100\084\111\067\108\111\115\101",g)end;(Promise.race({Promise.fromEvent(w.Event),Promise.fromEvent(H.AncestryChanged,function()return not H:IsDescendantOf(game)end)})):andThen(function()(((B:SaveAsync()):andThen(function()print("\112\108\097\121\101\114 \108\101\102\116\044 \115\097\118\101\100",q)end)):catch(function(I)warn("\101\114\114\111\114 \119\104\101\110 \112\108\097\121\101\114 \108\101\102\116\033",I)end)):finally(function()i=true A:Fire()end)return(Promise.delay(40)):andThen(function()DataStoreCache[H]=nil O=nil end)end)if not DataStoreCache[H]then DataStoreCache[H]={}end DataStoreCache[H][q]=B return B end DataStore2.Constants=Constants return setmetatable(DataStore2,DataStore2)
--[[**
	<description>
	Run this once to combine all keys provided into one "main key".
	Internally, this means that data will be stored in a table with the key mainKey.
	This is used to get around the 2-DataStore2 reliability caveat.
	</description>

	<parameter name = "mainKey">
	The key that will be used to house the table.
	</parameter>

	<parameter name = "...">
	All the keys to combine under one table.
	</parameter>
**--]]
function DataStore2.Combine(mainKey, ...)
	for _, name in ipairs({ ... }) do
		combinedDataStoreInfo[name] = mainKey
	end
end

function DataStore2.ClearCache()
	DataStoreCache = {}
end

function DataStore2.SaveAll(player)
	if DataStoreCache[player] then
		for _, dataStore in pairs(DataStoreCache[player]) do
			if dataStore.combinedStore == nil then
				dataStore:Save()
			end
		end
	end
end

DataStore2.SaveAllAsync = Promise.promisify(DataStore2.SaveAll)

function DataStore2.PatchGlobalSettings(patch)
	for key, value in pairs(patch) do
		assert(Settings[key] ~= nil, "No such key exists: " .. key)
		-- TODO: Implement type checking with this when osyris' t is in
		Settings[key] = value
	end
end

function DataStore2.__call(_, dataStoreName, player)
	assert(
		typeof(dataStoreName) == "string" and IsPlayer.Check(player),
		("DataStore2() API call expected {string dataStoreName, Player player}, got {%s, %s}"):format(
			typeof(dataStoreName),
			typeof(player)
		)
	)

	if DataStoreCache[player] and DataStoreCache[player][dataStoreName] then
		return DataStoreCache[player][dataStoreName]
	elseif combinedDataStoreInfo[dataStoreName] then
		local dataStore = DataStore2(combinedDataStoreInfo[dataStoreName], player)

		dataStore:BeforeSave(function(combinedData)
			for key in pairs(combinedData) do
				if combinedDataStoreInfo[key] then
					local combinedStore = DataStore2(key, player)
					local value = combinedStore:Get(nil, true)
					if value ~= nil then
						if combinedStore.combinedBeforeSave then
							value = combinedStore.combinedBeforeSave(clone(value))
						end
						combinedData[key] = value
					end
				end
			end

			return combinedData
		end)

		local combinedStore = setmetatable({
			combinedName = dataStoreName,
			combinedStore = dataStore,
		}, {
			__index = function(_, key)
				return CombinedDataStore[key] or dataStore[key]
			end,
		})

		if not DataStoreCache[player] then
			DataStoreCache[player] = {}
		end

		DataStoreCache[player][dataStoreName] = combinedStore
		return combinedStore
	end

	local dataStore = {
		Name = dataStoreName,
		UserId = player.UserId,
		callbacks = {},
		beforeInitialGet = {},
		afterSave = {},
		bindToClose = {},
	}

	dataStore.savingMethod = SavingMethods[Settings.SavingMethod].new(dataStore)

	setmetatable(dataStore, DataStoreMetatable)

	local saveFinishedEvent, isSaveFinished = Instance.new("BindableEvent"), false
	local bindToCloseEvent = Instance.new("BindableEvent")

	local bindToCloseCallback = function()
		if not isSaveFinished then
			-- Defer to avoid a race between connecting and firing "saveFinishedEvent"
			Promise.defer(function()
				bindToCloseEvent:Fire() -- Resolves the Promise.race to save the data
			end)

			saveFinishedEvent.Event:Wait()
		end

		local value = dataStore:Get(nil, true)

		for _, bindToClose in ipairs(dataStore.bindToClose) do
			bindToClose(player, value)
		end
	end

	local success, errorMessage = pcall(function()
		game:BindToClose(function()
			if bindToCloseCallback == nil then
				return
			end

			bindToCloseCallback()
		end)
	end)
	if not success then
		warn("DataStore2 could not BindToClose", errorMessage)
	end

	Promise.race({
		Promise.fromEvent(bindToCloseEvent.Event),
		Promise.fromEvent(player.AncestryChanged, function()
			return not player:IsDescendantOf(game)
		end),
	}):andThen(function()
		dataStore
			:SaveAsync()
			:andThen(function()
				print("player left, saved", dataStoreName)
			end)
			:catch(function(error)
				-- TODO: Something more elegant
				warn("error when player left!", error)
			end)
			:finally(function()
				isSaveFinished = true
				saveFinishedEvent:Fire()
			end)

		--Give a long delay for people who haven't figured out the cache :^(
		return Promise.delay(40):andThen(function()
			DataStoreCache[player] = nil
			bindToCloseCallback = nil
		end)
	end)

	if not DataStoreCache[player] then
		DataStoreCache[player] = {}
	end

	DataStoreCache[player][dataStoreName] = dataStore

	return dataStore
end

DataStore2.Constants = Constants

return setmetatable(DataStore2, DataStore2)
