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

local function wrap_span(arg, class)
	if arg == nil then
		return nil
	else
		return '<span class="' .. class .. '">' .. arg .. '</span>'
	end
end

local function ref_segment(frame, args)
	local function category_of_change(args)
		if args[1] == nil and args[2] ~= nil then
	        return args[2] .. " inserted"
	    elseif args[1] ~= nil and args[2] == nil then
	    	return args[1] .. " removed"
	    elseif args[1] ~= nil and args[2] ~= nil then
	    	return args[1] .. " amended to " .. args[2]
	    end
    end
	args[1] = wrap_span(args[1], "errata-original")
	args[2] = wrap_span(args[2], "errata-correction")
	local msg = "Errata correction: " .. category_of_change(args)
	-- details link
	if args[3] ~= nil then
		msg = msg .. '  ([[' .. args[3] .. '|details]])'
	end
    -- wrap in <ref> tags
	return frame:extensionTag('ref', msg, {group = 'errata'})
end

function p.errata(frame)
	local args = getArgs(frame)
	
	-- {{{2}}} or empty
	local text = "";
	if args[2] ~= nil then text = args[2] end
	
	return text .. ref_segment(frame, args)
end

return p