--Internal functions

function DataStore:Debug(...)
	if Debug then
		print(...)
	end
end

function DataStore:_GetRaw()
	if not self.getQueue then
		self.getQueue = {}
	end

	if self.getting then
		self:Debug("A _GetRaw is already in motion, just wait until it's done")
		local event = Instance.new("BindableEvent")
		self.getQueue[#self.getQueue + 1] = event
		event.Event:wait()
		self:Debug("Aaand we're back")
		return
	end

	self.getting = true

	local success, mostRecentKeyPage = pcall(function()
		return self.orderedDataStore:GetSortedAsync(false, 1):GetCurrentPage()[1]
	end)

	if not success then
		self.getting = false
		error(mostRecentKeyPage)
	end

	if mostRecentKeyPage then
		local recentKey = mostRecentKeyPage.value
		self:Debug("most recent key", mostRecentKeyPage)
		self.mostRecentKey = recentKey
		local success, value = pcall(function()
			return self.dataStore:GetAsync(recentKey)
		end)
		if not success then
			self.getting = false
			error(value)
		end
		self.value = value
	else
		self:Debug("no recent key")
		self.value = nil
	end

	for _, waiting in pairs(self.getQueue) do
		self:Debug("resuming in queue", waiting)
		waiting:Fire()
	end

	self.getQueue = {}
	self.haveValue = true
	self.getting = false
end

function DataStore:_Update(dontCallOnUpdate)
	if not dontCallOnUpdate then
		for _,callback in pairs(self.callbacks) do
			callback(self.value, self)
		end
	end

	self.haveValue = true
	self.valueUpdated = true
end
