local export = {}

local m_number_list = require("Module:number list/sandbox")

local function compare_numbers(a, b)
	if type(a) ~= "number" then
		a = tonumber(a)
	end
	if type(b) ~= "number" then
		b = tonumber(b)
	end
	return a < b
end

function export.print_table(language_code)
	local module = require("Module:number list/data/" .. language_code)
	
	local lang = require("Module:languages").getByCode(language_code)
	local full_link = require("Module:links").full_link
	local tag_text = require("Module:script utilities").tag_text
	local function link(form)
		return full_link({ lang = lang, term = form})
	end
	local function tag(form)
		return tag_text(form, lang)
	end
	
	local form_types = m_number_list.get_number_types(language_code)
	local numeral_index = 1
	table.insert(form_types, numeral_index,
		{key = "numeral", display = "Numeral"})
	
	local number_type_indices = {}
	for number, data in pairs(module.numbers) do
		for i, form_type in pairs(form_types) do
			if data[form_type.key] then
				number_type_indices[i] = true
			end
		end
	end
	
	local numeral_config = module.numeral_config
	if numeral_config then
		number_type_indices[numeral_index] = true
	end
	
	number_type_indices = require("Module:table").keysToList(number_type_indices)
	
	local Array = require("Module:array")
	local output = Array()
	for number, data in require("Module:table").sortedPairs(module.numbers, compare_numbers) do
		local number_string
		if type(number) == "number" then
			number_string = ("%.0f"):format(number)
		else
			number_string = number
		end
		
		output:insert(("|-\n| %s"):format(number))
		
		local numeral
		if numeral_config then
			numeral = m_number_list.generate_decimal_numeral(numeral_config, number)
		elseif data.numeral then
			numeral = data.numeral
		end
		if numeral then
			numeral = tag(numeral)
			output:insert(("| %s"):format(numeral or ""))
		end
		
		for _, i in ipairs(number_type_indices) do
			if i ~= numeral_index then
				local form = data[form_types[i].key]
				if type(form) == "table" then
					form = Array(form):map(link):concat(", ")
				elseif form then
					form = link(form)
				end
				output:insert(("| %s"):format(form or ""))
			end
		end
	end
	
	-- Add headers.
	for i, index in ipairs(number_type_indices) do
		output:insert(i, ("! %s"):format(m_number_list.display_number_type(form_types[index])))
	end
	output:insert(1, ("! Number"))
	
	output:insert(1, '{| class="wikitable"')
	output:insert('|}')
	
	return output:concat("\n")
end

function export.table(frame)
	local language_code
	if frame then
		language_code = frame.args[1]
	end
	
	if not language_code then
		language_code = mw.title.getCurrentTitle().fullText:match("Module:number list/data/([a-z-]+)")
		if not language_code then
			error("No language code in title or in parameter 1.")
		end
		if language_code == "und" then
			return
		end
	end
	
	return export.print_table(language_code)
end

return export