local export = {}

local m_lang = require("Module:languages")
local link = require("Module:links").full_link
local serial_comma_join = require("Module:table").serialCommaJoin
local format_categories = require("Module:utilities").format_categories
local process = require("Module:parameters").process

local function make_header(terms, lang, full_name, sc, context)
	local term_links = {}
	for i,term in ipairs(terms) do
		term_links[i] = link({term = term, lang = lang, sc = sc}, "term")
	end
	
	return '<h2><span id="' .. full_name .. '">' .. full_name
		.. "</span> citations of "
		.. serial_comma_join(term_links)
		.. (context and ", in context of ''[[Appendix:" .. context .. "|" .. context .. "]]''" or "")
		.. "</h2>"
end

-- If the term is a valid pagename and there isn't an entry for it,
-- return a category.
local function is_undefined(term)
	local success, title = pcall(mw.title.new, term)
	if success and title then
		local existence
		success, existence = pcall(function() return title.exists end)
		if success and not existence then
			return true
		end
	end
	
	return false
end

function export.make_header_and_categories(frame)
	local title		= mw.title.getCurrentTitle()
	local namespace = title.nsText
	local baseText	= title.baseText

	local parent_args = frame:getParent().args
	local compat = parent_args["lang"]

	local params = {
		[compat and "lang" or 1] = { required = true },
		[compat and 1 or 2] = { list = true, default = baseText },
		lang2 = {},
		sc = {},
		ct = {}, -- context
		sort = {},
	}
	
	local args = process(parent_args, params)
	
	local lang_code = compat or args[1]
	local lang = m_lang.getByCode(lang_code) or m_lang.err(lang_code, "lang")
	local full_name = lang:getFullName()
	
	if args.lang2 then
		require("Module:debug").track("citations/lang2")
	end
	
	local sc = args.sc
	sc = sc and require("Module:scripts").getByCode(sc)
	
	local terms = args[compat and 1 or 2]
	
	local context = args.ct
	
	local text = {}
	
	table.insert(text, make_header(terms, lang, full_name, sc, context))
	
	if namespace == "Citations" then
		if args.sort then
			table.insert(text, "[[Category:Citations pages with manual sortkey]]")
		end
		
		for _, term in ipairs(terms) do
			if is_undefined(term) then
				table.insert(text, "[[Category:" .. full_name .. " citations of undefined terms|" .. term .. "]]")
				break
			end
		end
		
		if terms[2] then
			table.insert(text, "[[Category:Citations of multiple entries]]")
		end
		
		-- "true" to force output in Citations namespace, where [[Module:utilities]]
		-- may not continue to add categories.
		table.insert(text, format_categories({full_name .. " citations"},
			lang, args.sort, nil, true))
	end
	
	text = table.concat(text)
	
	if compat then
		text = frame:expandTemplate{
			title = "check deprecated lang param usage",
			args = {text, lang = lang_code}
		}
	end
	
	return text
end

return export