local babel = {}

function argtable( args )
	local p = {}
	for k, v in pairs( args ) do
		p[k] = v
	end
	return p
end

function babel.babelbox( frame )
	local arg = string.lower(frame.args[1] or "zh")
	local lang = string.match(arg, "^([a-z%-]-)%-[0-4n]$") or arg
	local level = string.match(arg, "^[a-z%-]-%-([0-4n])$") or "n"
	langobj = mw.getLanguage( lang )
	if not langobj then
		return frame:expandTemplate{ title = arg }
	end
	level = string.upper(level)
	local code = langobj:getCode()
	local langname = mw.language.fetchLanguageName( code )
	local dir = {[true]="rtl", [false]="ltr"}
	dir = dir[langobj:isRTL()]
	local cat
	if level == "N" then
		cat = lang.."_母语使用者"
	else
		cat = lang.."-"..level.."_使用者"
	end
	local content = frame:preprocess( mw.message.new( "babel-"..level ):inLanguage( lang ):params{':Category:'..cat, ':Category:'..lang..'_使用者', langname}:plain() )
	local text = '<div class="mw-babel-box mw-babel-box-'..level..[[" dir="ltr">
{|style=" padding: 0;  border-spacing: 0;"
! dir="ltr" | ]]..lang..'<span class="mw-babel-box-level-'..level..'">-'..level..[[</span>
| dir="]]..dir..'" lang="'..lang..'" | '..content..'\n|}\n</div>'
	return text
end

function babel.babel( frame )
	local args = argtable((frame:getParent() or frame).args)
	return frame:callParserFunction("#babel", args)
end

return babel