Modul:list of families/toplevel

local export = {}
local filters = {}

local function get_parent(families, code)
	if not families[code] then return nil end
	local parent = families[code][3]
	local last_parent = nil
	while true do
		if parent == nil or parent == "qfa-not" then
			return last_parent
		end
		
		last_parent = parent
		if not families[parent] then
			return nil
		end
		
		parent = families[parent][3]
	end
end

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

	for code, _ in pairs(families) do
		if not get_parent(families, data) then
			stats[code] = { langs = {}, subfams = {} }
		end
	end 

	for code, data in pairs(languages) do
		local family_code = data[3]
		family_code = get_parent(families, family_code) or family_code
		local fdata = stats[family_code]
		if fdata then
			table.insert(fdata.langs, code)
		end
	end

	for code, data in pairs(families) do
		local family_code = data[3]
		family_code = get_parent(families, family_code) or family_code
		local fdata = stats[family_code]
		if fdata then
			table.insert(fdata.subfams, code)
		end
	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]

		if not get_parent(families, code) then
			local rt = nil
			if data.otherNames then
				local i = 1
				rt = {}
				while data.otherNames[i] do
					table.insert(rt, data.otherNames[i])
					i = i + 1
				end
			end
	
			if (not filter) or filter(code, data, args) then
				local catname = (data[1]:find("[Bb]ahasa-bahasa") and "" or "Bahasa-bahasa ") .. data[1]
				catname = catname:sub(1, 1):upper() .. catname:sub(2)
	
				table.insert(rows, string.format(
					' id="%s"\n' ..
					'| <code>%s</code>\n' ..
					'| [[:Kategori:%s|%s]]\n' ..
					'| %s\n' ..
					'| %u\n' ..
					'| %u\n',
					code, code,
					catname, data[1],
					rt and table.concat(rt, ", ") or "&nbsp;",
					#stats[code].subfams,
					#stats[code].langs
				))
			end
		end
	end

	return
		"{| class=\"wikitable sortable\"\n" ..
		"! Kod\n" ..
		"! Nama berkanun\n" ..
		"! Nama lain\n" ..
		"! Semua subkeluarga\n" ..
		"! Semua bahasa\n" ..
		"|-" .. table.concat(rows, "\n|-") .. "\n|}"
end

filters["three-letter code"] = function (code, data, args)
	local firstletter = args[2]
	return data[3] ~= "qfa-not" and code:find("^" .. (firstletter or "[a-z]") .. "[a-z][a-z]$") ~= nil
end

filters["exceptional"] = function (code, data, args)
	return data[3] ~= "qfa-not" and code:find("-") ~= nil
end

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

return export