Module:User:Victar/lectlabel

local export = {}

local m_languages = require("Module:languages")

local function errorf(level, ...)
	if type(level) == number then
		return error(string.format(...), level + 1)
	else -- level is actually the format string.
		return error(string.format(level, ...), 2)
	end
end

local function logf(...)
	return mw.log(string.format(...))
end

function export.etyl(frame)
	local params = {
		[1] = {}, -- parent language code?
		[2] = {list = true},
		["sort"] = {},
	}
	local args = require("Module:parameters").process(frame:getParent().args, params)
	
	local sort_key = args["sort"]
	
	local lang = m_languages.getByCode(args[1]) or m_languages.err(args[1], 1)
	local langCode = lang:getCode()
	
	local lects = args[2]
	
	for i, lect in ipairs(lects) do
		local langObject = require("Module:etymology languages").getByCode(lect)
		if langObject then
			-- Imperfect: some etymology languages are probably farther away
			-- generationally than daughters.
			if langObject:getParentCode() ~= langCode then
				logf("%s (%s) is not the parent of %s (%s)",
					lang:getCanonicalName(), langCode,
					langObject:getCanonicalName(), langObject:getCode())
			end
			lects[i] = langObject:makeWikipediaLink()
		else
			errorf("The language code %s is not recognized", lect)
		end
	end
	
	if not lects[1] then
		return frame.args.default
	else
		return require "Module:table".serialCommaJoin(lects)
	end

end

return export