require('strict')

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

function p.lookup(abr)
	local data = mw.loadData('Module:Lalisabr/data')
	local newdata = {}
	for index, value in ipairs(data) do
		newdata[value[1]] = {value[2], value[4]}
    end
	local expanded = newdata[abr]
	assert (expanded, "Unrecognised abbreviation: " .. abr)
	return expanded
end

function p.makeTable(frame)
	local tableStart = '<table width="600px" style="margin:0 auto; background-color:transparent;color:inherit;">\n'
	local tableEnd = '</table>'
	local data = mw.loadData('Module:Lalisabr/data')
	local args = getArgs(frame)
	local initial = args[1]
	local final = args[2]
	local output = ""
	local started = nil
	for index, value in ipairs(data) do
		if value[1] == initial or started then
			output = output .. "{{Dotted summary row no image|1={{nowrap|1=<i>"
				.. value[1]
				.. "</i> = "
				.. value[2]
				.. "&nbsp;}}|2=&nbsp;{{nowrap|"
				.. value[3]
				.. "}}}}\n"
			started = 1
		end

		if value[1] == final then
			return frame:preprocess(tableStart .. output .. tableEnd)
		end
	end
end

--[=[
Construct the abbbreviation span
]=]
function p._abbreviation(args)
	local span = mw.html.create("span")
	
	local data = p.lookup(args[1]);
	local title = data[1];
	local link = data[2];
	
	local wikitext = "<i>" .. args[1] .. "</i>";
	if link ~= nil then
		wikitext = "[[" .. link .. "|" .. wikitext .. "]]"
	end
	
	span:attr("title", title):wikitext(wikitext)
	
	return tostring(span)
end

function p.abbreviation(frame)
	return p._abbreviation(getArgs(frame))
end

return p