function DataStore2.Combine(t,...)for P,W in pairs({...})do combinedDataStoreInfo[W]=t end end function DataStore2.ClearCache()DataStoreCache={}end function DataStore2.SaveAll(t)if DataStoreCache[t]then for t,P in pairs(DataStoreCache[t])do if P.combinedStore==nil then P:Save()end end end end function DataStore2.PatchGlobalSettings(t)for t,P in pairs(t)do assert(Settings[t]~=nil,"\078\111 \115\117\099\104 \107\101\121 \101\120\105\115\116\115\058 "..t)Settings[t]=P end end function DataStore2.__call(t,P,W)assert(typeof(P)=="\115\116\114\105\110\103"and typeof(W)=="\073\110\115\116\097\110\099\101",("\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 \073\110\115\116\097\110\099\101 \112\108\097\121\101\114\125\044 \103\111\116 \123\037\115\044 \037\115\125"):format(typeof(P),typeof(W)))if DataStoreCache[W]and DataStoreCache[W][P]then return DataStoreCache[W][P]elseif combinedDataStoreInfo[P]then local t=DataStore2(combinedDataStoreInfo[P],W)t:BeforeSave(function(t)for P in pairs(t)do if combinedDataStoreInfo[P]then local Y=DataStore2(P,W)local b=Y:Get(nil,true)if b~=nil then if Y.combinedBeforeSave then b=Y.combinedBeforeSave(clone(b))end t[P]=b end end end return t end)local Y=setmetatable({combinedName=P,combinedStore=t},{__index=function(P,W)return CombinedDataStore[W]or t[W]end})if not DataStoreCache[W]then DataStoreCache[W]={}end DataStoreCache[W][P]=Y return Y end local Y={}Y.Name=P Y.UserId=W.UserId Y.callbacks={}Y.beforeInitialGet={}Y.afterSave={}Y.bindToClose={}Y.savingMethod=SavingMethods[Settings.SavingMethod].new(Y)setmetatable(Y,DataStoreMetatable)local b,i=Instance.new("\066\105\110\100\097\098\108\101\069\118\101\110\116"),false game:BindToClose(function()if not i then spawn(function()W.Parent=nil end)b.Event:wait()end local t=Y:Get(nil,true)for P,Y in pairs(Y.bindToClose)do Y(W,t)end end)local D D=W.AncestryChanged:Connect(function()if W:IsDescendantOf(game)then return end D:Disconnect();(((Y:SaveAsync()):andThen(function() end)):catch(function(t) end)):finally(function()b:Fire()i=true end)delay(40,function()DataStoreCache[W]=nil end)end)if not DataStoreCache[W]then DataStoreCache[W]={}end DataStoreCache[W][P]=Y return Y end DataStore2.Constants=Constants return setmetatable(DataStore2,DataStore2)

function DataStore2.Combine(mainKey, ...)
	for _, name in pairs({...}) 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

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 typeof(player) == "Instance",
		("DataStore2() API call expected {string dataStoreName, Instance 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 = {}

	dataStore.Name = dataStoreName
	dataStore.UserId = player.UserId

	dataStore.callbacks = {}
	dataStore.beforeInitialGet = {}
	dataStore.afterSave = {}
	dataStore.bindToClose = {}
	dataStore.savingMethod = SavingMethods[Settings.SavingMethod].new(dataStore)

	setmetatable(dataStore, DataStoreMetatable)

	local event, fired = Instance.new("BindableEvent"), false

	game:BindToClose(function()
		if not fired then
			spawn(function()
				player.Parent = nil -- Forces AncestryChanged to fire and save the data
			end)

			event.Event:wait()
		end

		local value = dataStore:Get(nil, true)

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

	local playerLeavingConnection
	playerLeavingConnection = player.AncestryChanged:Connect(function()
		if player:IsDescendantOf(game) then return end
		playerLeavingConnection:Disconnect()
		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()
			event:Fire()
			fired = true
		end)

		delay(40, function() --Give a long delay for people who haven't figured out the cache :^(
			DataStoreCache[player] = 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)
