local m_lb = require("Module:labels")
local export = {}

function export.show(frame)
	local args = frame:getParent().args
	local pagename = mw.title.getCurrentTitle().text

	if (args[1] == nil and mw.title.getCurrentTitle().nsText == "Template") then
		args[1] = "und"
	end
	
	local lang = require("Module:languages").getByCode(args[1]) or error("The language code \"" .. args[1] .. "\" is not valid.")
	local nocat = args["nocat"] ~= nil
	local script = args["script"] or nil
	local script2 = args["script2"] or nil
	local sort_key = args["sort"] or pagename
	local sort_key2 = args["sort2"] or pagename
	local term_mode = (frame.args["term"]) ~= nil
	local labels = get_labels(args, require("Module:languages").getByCode(args[1]):getCanonicalName())
	
	return m_lb.show_labels(labels, lang, script, script2, sort_key, sort_key2, nocat, term_mode)
end


function get_labels(args, langname)

	local labels = {}
	local indtr = ""
	local i = 2
	local q = nil
	local first = true;
	
	if (args["intr"] ~= nil) then 
		indtr = indtr .. "[[intransitive]], or "
	end
	
	
	while (args[i] ~= nil) do
	
		if (mw.ustring.sub(args[i], 0, 1) == ".") then
			table.insert(labels, mw.ustring.sub(args[i], 2));
		else
			if (first == false) then
				indtr = indtr .. " or "
			else
				if (args["cop"] ~= nil and args["ditr"] ~= nil) then
					indtr = indtr .. "[[ditransitive]], [[copulative]] with "
				elseif (args["cop"] ~= nil) then
					indtr = indtr .. "[[copulative]] with "
				elseif (args["ditr"] ~= nil) then
					indtr = indtr .. "[[ditransitive]], with the indirect object taking "
				elseif (args["aux"] ~= nil) then
					indtr = indtr .. "[[auxiliary]] with "
				else
					indtr = indtr .. "[[transitive]] with "
				end
				first = false
			end
			
			if (mw.ustring.sub(args[i], 0, 1) == "-") then
				indtr = indtr ..  mw.ustring.sub(args[i], 2);
			else
				indtr = indtr .. "'''[[" .. args[i] .. "#" .. langname .. "|" .. args[i] .. "]]'''"
			end
			indtr = indtr .. qualifier(args[("qual" .. (i-1))])
		end
		i = i + 1
	end
	
	if (args["direct"] ~= nil) then 
		if (args["ditr"] ~= nil) then
			indtr = indtr .. " or no preposition"
		else
			indtr = indtr .. " or with no preposition"
		end
		indtr = indtr .. qualifier(args["qualdirect"])
	end
	
	if (args["aux"] ~= nil) then
		indtr = indtr .. " and a verb in the " .. args["aux"]
	elseif (args["cop"] ~= nil and args["ditr"] ~= nil) then
		indtr = indtr .. " for the second object"
	end
	
	table.insert(labels, indtr)
	return labels

end


function qualifier(text)
	if (text == nil or text == "") then return "" end
	return '&nbsp;<span class="ib-brac"><span class="qualifier-brac">(</span></span><span class="ib-content"><span class="qualifier-content">' .. text ..
'</span></span><span class="ib-brac"><span class="qualifier-brac">)</span></span>'
end

return export