
-- This piece of code just created for appending metadata to the end of a file and reading it.
-- Nothing fancy

module("RSC.Metadata", package.seeall)

METADATA_HEADER = "RSC\xa1\xf3"
CURRENT_VERSION = 1

function AppendMetadata(fileName, metadata)
	if istable(metadata) then metadata = util.TableToJSON(metadata) end
	assert(isstring(metadata))

	local f = file.Open(fileName, "ab", "DATA")
	if not f then return RSC.Log("error", "Failed to append metadata to %s", file) end

	f:Write(metadata)
	f:WriteULong(#metadata)
	f:Write(METADATA_HEADER)

	f:Close()
end

function ReadMetadata(fileName)
	local f = file.Open(fileName, "rb", "DATA")
	if not f then return RSC.Log("error", "Failed to append metadata to %s", file) end

	f:Seek(f:Size() - #METADATA_HEADER)

	local metadata
	if f:Read(#METADATA_HEADER) == METADATA_HEADER then
		f:Skip(-#METADATA_HEADER - 4)
		local size = f:ReadULong()

		f:Skip(-size - 4)
		local json = f:Read(size)
		if json then metadata = util.JSONToTable(json) end
	end
	-- while f:Tell() > f:Size() - 4096 do
	--	 local header = f:Read(#METADATA_HEADER)
	--	 f:Skip(-#METADATA_HEADER - 1)

	--	 if #header == #METADATA_HEADER and header == METADATA_HEADER then
	--		 f:Skip(-3)
	--		 local size = f:ReadULong()

	--		 f:Skip(-4 - size)
	--		 local json = f:Read(size)
	--		 if json then metadata = util.JSONToTable(json) end
	--		 break
	--	 end
	-- end

	f:Close()
	return metadata
end
