Module:DropList

Revision as of 03:12, 17 October 2015 by がか (talk | contribs) (fix displaying for unknown diff.)

Documentation for this module may be created at Module:DropList/doc

local DropList = {}

function trim(str)
	return str:match('^%s*(.-)%s*$')
end

local args_grammar = {
	comma_list = '[^,]+',
	ship       = '^%s*(.-)%s*:%s*(.-)%s*$',
	node_name  = '%s*(%a+)%s*/?',
	node_diff  = '/%s*(%a+)%s*$'
}

local colors = {
	['Easy']   = '5a5',
	['Medium'] = 'da6',
	['Hard']   = 'd33'
}

function parseArgs(args)

	local table = { nodes = {}, rows = {} }

	-- header args
	for node in string.gmatch(args.nodes, args_grammar.comma_list) do
		local node = trim(node)
		table.nodes[#table.nodes + 1] = { name = node }
		if node == args.boss then
			table.nodes[#table.nodes].boss = true
		end
	end

	-- ship args
	for arg_name, arg in pairs(args) do
		if tonumber(arg_name) then
			local ship, nodes = arg:match(args_grammar.ship)
			-- TODO: check ship existence?
			table.rows[ship] = {}
			local row = table.rows[ship]
			row.ship = ship
			row.nodes = {}
			for _, node in pairs(table.nodes) do
				row.nodes[node.name] = node
			end
			for node_diff in string.gmatch(nodes, args_grammar.comma_list) do
				local node = node_diff:match(args_grammar.node_name)
				local diff = node_diff:match(args_grammar.node_diff)
				-- TODO: check node/difficulty existence?
				if diff and colors[diff] then
					row.nodes[node] = { color = colors[diff], diff = diff .. '+' }
				else
					row.nodes[node] = { color = "0ff", diff = '?' }
				end
			end
		end
	end

	return table

end

local table_format = {
	header           = '{| class="wikitable sortable" align="center" width="90%" style="text-align:center"\n!Ship\n',
	header_node      = '!width="10%%"|%s\n',
	header_boss_node = '!width="10%%" style="background-color:pink;color:red;"|\'\'\'%s\'\'\'\n',
	ship_cell        = '|-\n|[[%s]]\n',
	node_cell        = '|style="background-color:#%s;"|%s\n',
	empty_cell       = '|\n',
	footer           = '|}\n'
}

function showTable(table)

	local res = table_format.header

	-- header
	for _, node in pairs(table.nodes) do
		if node.boss then
			res = res .. string.format(table_format.header_boss_node, node.name)
		else
			res = res .. string.format(table_format.header_node, node.name)
		end
	end

	-- rows
	for ship, row in pairs(table.rows) do
		res = res .. string.format(table_format.ship_cell, ship)
		for _, node in pairs(table.nodes) do
			local node = row.nodes[node.name]
			if node.color then
				if node.diff then
					res = res .. string.format(table_format.node_cell, node.color, node.diff)
				else
					res = res .. string.format(table_format.node_cell, node.color, "?")
				end
			else
				res = res .. table_format.empty_cell
			end
		end
	end

	res = res .. table_format.footer

	return res

end

function DropList.show(frame)
	return showTable(parseArgs(frame.args))
end

return DropList