Module:table of contents

local export = {}

local m_languages = require("Module:languages")

local function makeUrl(title, queryType, from)
	if title and title.fullUrl then
		if from then
			if queryType then
				local query = { [queryType] = from }
				return title:fullUrl(query, "https")
			else
				return title:fullUrl(nil, "https")
			end
		end
	end
end

local function link(title, queryType, from, display, lang, script)
	local url = makeUrl(title, queryType, from)
	if url then
		local ext_link = "[" .. url .. " " .. ( display or from ) .. "]"
		if lang then
			return '<span class="' .. script .. '" lang="' .. lang .. '">' .. ext_link .. "</span>"
		elseif script then
			return '<span class="' .. script .. '">' .. ext_link .. "</span>"
		else
			return ext_link
		end
	end
end

function export.show(frame)
	local output = {}
	local queryType
	
	local params = {
		[1] = { list = true },
		["lang"] = { type = "string" },
		["subcat"] = { type = "boolean" },
		["top"] = {},
	}
	
	local args = require("Module:parameters").process(frame.args[1] and frame.args or frame:getParent().args, params)
	
	local lang = args.lang and m_languages.getByCode(args.lang) or nil
	local title = mw.title.getCurrentTitle()
	
	local froms = args[1]
	local display = {}
	
	for i, from in pairs(froms) do
		if mw.ustring.match(from, ":") then
			local from, linktext = mw.ustring.match(from, "([^:]+):(.+)")
			if from then
				froms[i] = lang and (lang:makeSortKey(from)) or from
				display[i] = linktext
			else
				error('Parameter ' .. i .. ' is badly formatted. It should contain a key to use in the link, a colon, and then the displayed text.')
			end
		else
			froms[i] = lang and (lang:makeSortKey(from)) or from
			display[i] = from
		end
	end
	
	local script = lang and lang:findBestScript(table.concat(args[1])):getCode() or (table.concat(args[1]) ~= "" and require("Module:scripts").findBestScriptWithoutLang(table.concat(args[1])):getCode())
	
	local subcat = args.subcat
	if subcat then
		queryType = "subcatfrom"
		-- [[Special:WhatLinksHere/Template:tracking/table-of-contents/subcat]]
		require("Module:debug").track("table-of-contents/subcat")
	else
		queryType = "from"
	end
	
	if args.top then
		local link = link(title, nil, args.top)
		table.insert(output, link)
		if froms and froms[1] then
			table.insert(output, " – ")
		end
	end
	
	for i, from in ipairs(froms) do
		local link = link(title, queryType, from, display[i], lang and lang:getCode() or nil, script)
		table.insert(output, link)
	end
	
	if not lang then table.insert(output, "[[Category:User:Theknightwho/table of contents]]") end
	
	return table.concat(output, " ")
end

return export