local export = {}

local term_module, homonym_module = "Module:R:TotfEty/data", "Module:R:TotfEty/homonyms"
local base_path = "https://www.arcanum.com/hu/online-kiadvanyok/Lexikonok-magyar-etimologiai-szotar-F14D3"

local function _sense_and_link(term, number, sense)
	local code
	if not number then
		local single_match = require(term_module)(term)
		if not single_match then
			local homonyms = require(homonym_module)(term)
			if not homonyms then
				error("No data for " .. term .. " in [[" .. term_module
					.. "]] or [[" .. homonym_module .. "]]")
			else
				homonyms = require("Module:array")(homonyms)
				local i = 0
				error("Choose from one of the following homonyms and place its "
					.. "number in the first parameter: "
					.. homonyms
						:map(function(homonym)
							i = i + 1
							return "[" .. base_path .. homonym .. " " .. i .. "]"
						end)
						:concat(", "))
			end
		end
		code = single_match
	else
		local homonyms = require(homonym_module)(term)
		if not homonyms then
			error("No data for " .. term .. " in [[".. homonym_module
				.. "]]")
		end
		code = homonyms[number]
		if not code then
			error("No homonym #" .. number .. " for " .. term
				.. " in [[" .. homonym_module .. "]]")
		end
	end
	if code then
		local link = "[" .. base_path .. code .. " " .. term .. "]"
		if sense then
			return require("Module:qualifier").sense({sense}) .. " " .. link
		else
			return link
		end
	else
		error("This should not happen")
	end
end

function export.sense_and_link(frame)
	local args = frame:getParent().args
	local title = args.title and assert(mw.title.new(args.title)) or mw.title.getCurrentTitle()
	
	-- Use args[1] as number if it's composed of only ASCII digits.
	local term, number
	if args[1] and args[1]:find "^%d+$" then
		number = tonumber(args[1])
	else
		term = args[1]
		if args[2] then
			number = tonumber(args[2])
			if not number then
				error("Parameter 2 should be a number if it is supplied")
			end
		end
	end
	
	local sense = args[2]
	if not term then
		if title.nsText == "Template" then
			return ""
		else
			term = title.text
		end
	end
	return _sense_and_link(term, number, sense)
end

return export