require('Module:No globals')
local getArgs = require('Module:Arguments').getArgs

local p = {}
local txt = {}

local function agg(...)
    local args = {...}
    for _, s in ipairs(args) do
        table.insert(txt, s)
    end
end

local function gcd(a,b)
	local r = a % b
	return r == 0 and b or gcd(b,r)
end

local function semplifica(t)
	local d
	if (t[1] >= t[2]) then d=gcd(t[1],t[2]) else d=gcd(t[2],t[1]) end
	return {t[1]/d,t[2]/d}
end

local function moltiplica(a,b)
	return semplifica({a[1]*b[1],a[2]*b[2]})
end

local function mostra(a)
	if (a[2] == 1) then
		return a[1]
	else
		return '<sup>'..a[1]..'</sup>⁄<sub>'..a[2]..'</sub>'
	end
end

function p.main(frame)
	local args = getArgs(frame, {
		valueFunc = function (key, value)
			if type(key) == "number" then
				if value == nil then
					return nil
				else
					value = mw.text.trim(value)
				end
			else
				if value == '' then return nil end
            end
			return value
		end
	})
	local uni = {}
	local n = 1
	local valore = 0
	local note = 0
	while (args['nome'..n]) do
		uni[n] = { nome = args['nome'..n], valore = args['valore'..n] or -1, unita = args['unit'..n] or '', nota = args['nota'..n] or '', numero = { tonumber(args['num'..n]) or 1, tonumber(args['den'..n]) or 1}, num = {1,1} }
		if (uni[n].nota ~= '') then note = 1 end
		if (uni[n].valore ~= -1) then valore = 1 end
		uni[n].numero = semplifica(uni[n].numero)
		n = n+1
	end
	n = n-1

	agg('{| class="wikitable" style="text-align:center"\n!colspan=',n,'|Nome')
	if (valore == 1) then agg('!!colspan=2|Valore') end
	if (note == 1) then agg(' !!Note') end
	for i, v in pairs(uni) do
		agg('\n|-\n|')
		for j=1,i-1 do
			uni[j].num = moltiplica(uni[j].num,v.numero)
			agg('style="background:#eee"|',mostra(uni[j].num),' ||')
		end
		agg('colspan=',n-i+1,' align=left|',v.nome)
		if (valore == 1) then
			if (v.valore == -1) then
				agg('|| || ')
			else
				agg('||align=right|',v.valore,' ||',v.unita)
			end
		end
		if (note == 1) then
			if (v.nota == '') then
				agg(' ||')
			else
				agg(' ||align=left|<small>',v.nota,'</small>')
			end
		end
	end
	agg('\n|}')
	return table.concat(txt)
end

return p