-- lx-bundle:true

local docstate = {}

-- Keep per-doc state weakly keyed so closed docs are collected
local state_by_doc = setmetatable({}, { __mode = "k" })

-- Resolve or create namespace map for one doc
local function ensure_doc_namespaces(doc)
	local doc_namespaces = state_by_doc[doc]
	if doc_namespaces then
		return doc_namespaces
	end
	doc_namespaces = {}
	state_by_doc[doc] = doc_namespaces
	return doc_namespaces
end

-- Get one namespaced value for a doc
function docstate.get(doc, namespace)
	if not doc then
		return nil
	end
	local doc_namespaces = state_by_doc[doc]
	if not doc_namespaces then
		return nil
	end
	return doc_namespaces[namespace]
end

-- Set one namespaced value for a doc
function docstate.set(doc, namespace, value)
	if not doc then
		return
	end
	local doc_namespaces = ensure_doc_namespaces(doc)
	doc_namespaces[namespace] = value
end

-- Remove one namespaced value for a doc
function docstate.remove(doc, namespace)
	if not doc then
		return
	end
	local doc_namespaces = state_by_doc[doc]
	if not doc_namespaces then
		return
	end
	doc_namespaces[namespace] = nil
	if next(doc_namespaces) == nil then
		state_by_doc[doc] = nil
	end
end

-- Remove all namespaced values for a doc
function docstate.clear_doc(doc)
	if not doc then
		return
	end
	state_by_doc[doc] = nil
end

return docstate
