local Q={}Q.__index=Q function Q.new(n)return setmetatable({_lockSession=n.lockSession,_readOnlyData=n.readOnlyData;_collection=n.collection;_currentData=nil;_dataLoaded=false,_closed=false},Q)end function Q.isClosed(Q)return Q._closed end function Q._load(Q)if Q._lockSession then return Q._lockSession:read()else return Q._readOnlyData end end function Q.read(Q)if Q._dataLoaded==false then local n=Q:_load()if n==nil then n=Q._collection.defaultData or{}end assert(Q._collection:validateData(n))Q._currentData=n Q._dataLoaded=true end return Q._currentData end function Q.write(n,Q)if n._lockSession==nil then error("\067\097\110\'\116 \119\114\105\116\101 \116\111 \097 \114\101\097\100\111\110\108\121 \068\111\099\117\109\101\110\116\068\097\116\097")end n._currentData=Q end function Q.save(Q)if Q._lockSession==nil then error("\067\097\110\'\116 \115\097\118\101 \111\110 \097 \114\101\097\100\111\110\108\121 \068\111\099\117\109\101\110\116\068\097\116\097")end Q._lockSession:write(Q._currentData)end function Q.close(Q)Q._closed=true if Q._lockSession then Q._lockSession:unlockWithFinalData(Q._currentData)end end return Q
local DocumentData = {}
DocumentData.__index = DocumentData

-- TODO: Backups

function DocumentData.new(options)
	return setmetatable({
		_lockSession = options.lockSession;
		_readOnlyData = options.readOnlyData;
		_collection = options.collection;
		_currentData = nil;
		_dataLoaded = false;
		_closed = false;
	}, DocumentData)
end

function DocumentData:isClosed()
	return self._closed
end

function DocumentData:_load()
	if self._lockSession then
		return self._lockSession:read()
	else
		return self._readOnlyData
	end
end

function DocumentData:read()
	if self._dataLoaded == false then
		local newData = self:_load()

		if newData == nil then
			newData = self._collection.defaultData or {}
		end

		assert(self._collection:validateData(newData))

		self._currentData = newData
		self._dataLoaded = true
	end

	return self._currentData
end

function DocumentData:write(value)
	if self._lockSession == nil then
		error("Can't write to a readonly DocumentData")
	end

	self._currentData = value
end

function DocumentData:save()
	if self._lockSession == nil then
		error("Can't save on a readonly DocumentData")
	end

	self._lockSession:write(self._currentData)
end

function DocumentData:close()
	self._closed = true

	if self._lockSession then
		self._lockSession:unlockWithFinalData(self._currentData)
	end
end

return DocumentData