require('strict')

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

local p = {}
local txt = {}

local function errhandler(msg)
	local cat = mw.title.getCurrentTitle().namespace == 0 and errorCategory or ''
	return string.format('<span class="error">%s</span>%s', msg, cat)
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] == 0) then
		return t
	end
	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[1] == 0) then
		error('Errore nei dati')
	else
		if (a[2] == 1) then
			return a[1]
		else
			return '<sup>'..a[1]..'</sup>⁄<sub>'..a[2]..'</sub>'
		end
	end
end

function p._main(args)
	local uni = {}
	local n = 1
	local valore = false
	local note = false
	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 0, tonumber(args['den'..n]) or 1},
			num = {1,1}
		}
		if (uni[n].nota ~= '') then note = true end
		if (uni[n].valore ~= -1) then valore = true end
		uni[n].numero = semplifica(uni[n].numero)
		n = n+1
	end
	n = n-1
	local bTabella = mw.html.create('table')
		:addClass('wikitable'):css({['text-align']='center'})
	local bRiga = mw.html.create('tr')
	bRiga:node(mw.html.create('th'):attr({['colspan']=n}):wikitext('Nome'))
	if (valore == true) then
		bRiga:node(mw.html.create('th'):attr({['colspan']=2}):wikitext('Valore'))
	end
	if (note == true) then
		bRiga:node(mw.html.create('th'):wikitext('Note'))
	end
	bTabella:node(bRiga)
	for i, v in pairs(uni) do
		local bRiga = mw.html.create('tr')
		for j=1,i-1 do
			uni[j].num = moltiplica(uni[j].num,v.numero)
			bRiga:node(mw.html.create('td'):css('background','#eee'):wikitext(mostra(uni[j].num)))
		end
		bRiga:node(mw.html.create('td'):attr({['colspan']=n-i+1,['align']='left'}):wikitext(v.nome))
		if (valore == true) then
			if (v.valore == -1) then
				bRiga:node(mw.html.create('td'):attr({['colspan']=2}))
			else
				bRiga:node(mw.html.create('td'):wikitext(v.valore))
				bRiga:node(mw.html.create('td'):wikitext(v.unita))
			end
		end
		if (note == true) then
			if (v.nota == '') then
				bRiga:node(mw.html.create('td'):wikitext(''))
			else
				bRiga:node(mw.html.create('td'):attr({['align']='left'}):wikitext('<small>'..v.nota..'</small>'))
			end
		end
		bTabella:node(bRiga)
	end
	return tostring(bTabella)
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
	})
	return p._main(args)
end

return p