require('strict')
local TableTools = require('Module:TableTools')
local getArgs = require('Module:Arguments').getArgs
local p = {}

local raw_styles = mw.loadData('Module:Table style/data')
local styles = {}
for k, v in pairs(raw_styles) do
	local style = v.style
	local names = v.aliases
	styles[k] = style
	for _, name in pairs(names) do
		styles[name] = style
	end
end

function p.main(frame)
	local args = getArgs(frame)
	return p._main(args)
end

function p._main(args)
	local str = ""
	for _, arg in pairs(args) do
		if styles[arg] ~= nil and styles[arg] ~= '' then
	    	str = str .. styles[arg]
	    else
	    	str = str .. arg .. ";"
	    end
	end
	if str ~= '' then
		-- Only add attribute wrapper if any valid style codes were given.
		str = 'style="' .. str .. '"'
	end
	return str
end

function p.supported_codes(frame)
	frame = mw.getCurrentFrame()
	local t = mw.html.create('table')
		:addClass('wikitable')
		:addClass('sortable')
	t:tag('tr')
		:tag('th'):wikitext('Code')
		:tag('th'):wikitext('Aliases')
		:tag('th'):wikitext('Output CSS Style')
	for k, v in TableTools.sortedPairs(raw_styles, function(a, b) return a < b end) do
		local row = t:tag('tr')
		row:tag('td'):tag('code'):wikitext(k)
		local aliasList = frame:expandTemplate{
			title = 'bulleted list',
			args = v.aliases
		}
		row:tag('td'):wikitext(aliasList)
		row:tag('td'):tag('code'):wikitext(v.style)
	end
	return t
end

return p