Documentation for this module may be created at Module:list of families/doc

local export = {}
local filters = {}

function export.show(frame)
	local args = frame.args
	local filter = filters[args[1]]
	local families = mw.loadData("Module:families/data")
	local languages = mw.loadData("Module:languages/alldata")
	local stats = {}

	for code, _ in pairs(families) do
		stats[code] = { langs = {}, subfams = {} }
	end 

	for code, data in pairs(languages) do
		local fdata = stats[data.family] or { langs = {} }
		table.insert(fdata.langs, code)
	end

	for code, data in pairs(families) do
		local fdata = stats[data.family] or { subfams = {} }
		table.insert(fdata.subfams, code)
	end

	local codes = {}
 
	for code, _ in pairs(families) do
		table.insert(codes, code)
	end 
	table.sort(codes)
 
	local rows = {}
	for i, code in ipairs(codes) do
		local data = families[code]

		local rt = nil
		if data.names[2] then
			local i = 2
			rt = {}
			while data.names[i] do
				table.insert(rt, data.names[i])
				i = i + 1
			end
		end

		if (not filter) or filter(code, data, args) then
			local catname = data.names[1] .. (data.names[1]:find("[Ll]anguages") and "" or " languages")
			catname = catname:sub(1, 1):upper() .. catname:sub(2)

			table.insert(rows, string.format(
				' id="%s"\n' ..
				'| <tt>%s</tt>\n' ..
				'| [[:Category:%s|%s]]\n' ..
				'| %s\n' ..
				'| %s\n' ..
				'| %u\n' ..
				'| %u\n',
				code, code,
				catname, data.names[1],
				(data.family ~= "qfa-und") and ('[[#' .. data.family .. '|' .. families[data.family].names[1] .. ']]') or '',
				rt and table.concat(rt, ", ") or "&nbsp;",
				#stats[code].subfams,
				#stats[code].langs
			))
		end
	end

	return
		"{| class=\"wikitable sortable\"\n" ..
		"! Code\n" ..
		"! Canonical name\n" ..
		"! Parent family\n" ..
		"! Other names\n" ..
		"! Subfamilies\n" ..
		"! Languages\n" ..
		"|-" .. table.concat(rows, "\n|-") .. "\n|}"
end

filters["normal"] = function (code, data, args)
	return data.family ~= "qfa-not"
end

filters["special"] = function (code, data, args)
	return data.family == "qfa-not"
end

return export