local export = {}

function export.examples(frame)
	local beginning =
[[
{| class="wikitable"
]]
	local caption = "|+ "

	local headers = 
[[
! code !! result
]]
	
	local row_template =
[[
|-
| {{{code}}} ||{{{middle}}} {{{result}}}
]]

	local middle
	
	local close = "|}"

	local rows = {}
	
	local params = {
		[1] = { required = true, list = true },
		["caption"] = {},
		["header"] = { type = "boolean" },
	}
	
	local args = require("Module:parameters").process(frame:getParent().args, params)
	
	if args.caption then
		beginning = beginning .. caption .. args.caption .. "\n"
	end
	
	if args.header then
		beginning = beginning .. headers
		middle = ""
	else
		middle = " → || "
	end
	
	for i, example in ipairs(args[1]) do
		local lang, rest = mw.ustring.match(example, "^([^:]+)%:(.*)$")
		if lang then
			example = rest
		else
			error("Examples must be preceded by a language code prefix, followed by a colon")
		end
		
		local parameters = mw.text.split(example, "~")
		local template_params = {
			lang,
		}
		
		for _, parameter in ipairs(parameters) do
			table.insert(template_params, parameter)
		end
		
		local code = require("Module:template parser").templateLink("label", template_params)
		local result = require("Module:labels").show_labels {
			labels = parameters,
			lang = require("Module:languages").getByCode(lang, i, "allow etym"),
			nocat = true
		}
		
		local content = {
			code = code,
			middle = middle,
			result = result,
		}
		
		local function add_content(item)
			if content[item] then
				return content[item]
			end
		end
		
		local row = mw.ustring.gsub(row_template, "{{{(%w+)}}}", add_content)
		table.insert(rows, row)
	end
	
	return beginning .. table.concat(rows) .. close
end

return export