local m_links = require('Module:links')

local export = {}

local italicized_ranks = {
	["nothogenus"] = true,
	["subgenus"] = true,
	["genus"] = true,
	["subsection"] = true,
	["section"] = true,
	["subsect."] = true,
	["sect."] = true,
	["nothospecies"] = true,
	["infraspecies"] = true,
	["subspecies"] = true,
	["species"] = true,
	["variety"] = true,
	["forma"] = true
}

function page_exists(title)
	local link_object = mw.title.new(title) or nil
	if link_object then
		local link_id = link_object.id
		return link_object.id ~= 0 
	end
	return false			

end

function wikispecies_link(title, alt)
	local result = "[[Wikispecies:" .. title
	if alt then
		result = result .. "|" .. alt
	else
		result = result .. "|" .. title
	end
	return result .. "]]"
	
end

function export.main(frame)
	local params = {
		[1] = {required = true},
		[2] = {required = true},
		[3] = {},
		["i"] = {type = "boolean"}
	}
	local args = require("Module:parameters").process(frame:getParent().args, params)
	
	local lang = require('Module:languages').getByCode('mul')
	local taxon = args[1]
	local rank = args[2]
	local alt = args[3]
	
	local result = ""
	
	local exists = page_exists(taxon)
	
	if not exists then
		result = wikispecies_link(taxon, alt)
	else
		result = m_links.full_link({lang = lang, term = taxon, alt=alt})
	end
	
	if italicized_ranks[rank] or args["i"] then
		result = require("Module:italics").i(result)
	end
	
	if exists then
		result = result .. "<sup>" .. wikispecies_link(taxon, "ws") .. "</sup>"
	else
		result = result .. "[[Category:Entries using missing taxonomic name (" .. rank .. ")]]"
	end
	
	return result
	
end


return export