local export = {}

local m_links = require("Module:links")
local m_string_utils = require("Module:string utilities")

local ugsub = m_string_utils.gsub
local upper = m_string_utils.upper
local kana_to_romaji = require("Module:Hrkt-translit").tr

-- [[Module:languages]]
-- [[Module:parameters]]
-- [[Module:script utilities]]
-- [[Module:ja-ruby]]
-- [[Module:Hrkt-translit]]

function export.link(data, options)
	options = options or {}
	data.lang = data.lang or require'Module:languages'.getByCode'ja'

	local kana_for_rom = data.kana or data.lemma
	if not data.kana then
		data.lemma = data.lemma:gsub('[ %%%^%-%.]', '')
	end

	local ruby
	if data.kana and data.lemma ~= data.kana then
		ruby = require('Module:ja-ruby').ruby_auto{
			term = data.lemma,
			kana = data.kana,
			options = options.rubyOptions,
		}
	else
		require("Module:debug").track('ja-link/no ruby')
		ruby = data.lemma
	end

	if ruby:match'%[%[.+%]%]' then
		require("Module:debug").track('ja-link/manual wikilink')
		data.term = ruby
	elseif data.linkto == "" or data.linkto == "-" then
		require("Module:debug").track('ja-link/disabled link')
		data.alt = ruby
	else
		data.term = data.linkto or data.lemma:gsub('[ %%]', '')
		data.alt = ruby
	end

	if data.tr ~= '-' then
		if not data.tr then
			data.tr = m_links.remove_links(kana_to_romaji(kana_for_rom, data.lang:getCode(), nil, {hist = options.hist}))
			if options.caps then
				require("Module:debug").track("ja-link/caps")
				data.tr = ugsub(data.tr, "%f[^%s%c%p]%l", upper)
			end
		else
			if options.hist then require("Module:debug").track("ja-link/parameter hist unused") end
		end
		data.tr = require("Module:script utilities").tag_translit(data.tr, data.lang:getCode(), "term")
	end
	
	data.lemma = nil
	data.kana = nil
	data.linkto = nil

	return m_links.full_link(data, options.face, not options.disableSelfLink)
end

function export.show(frame)
	local alias_of_3 = {alias_of = 3}
	local boolean = {type = "boolean"}
	local plain = {}
	local args = require("Module:parameters").process(frame:getParent().args, {
		[1] = {required = true},
		[2] = plain,
		[3] = plain,
		['gloss'] = alias_of_3,
		['t'] = alias_of_3,
		['linkto'] = {allow_empty = true},
		['rom'] = plain,
		['lit'] = plain,
		['pos'] = plain,
		['id'] = plain,
		['hist'] = boolean,
		['caps'] = boolean,
		['self'] = {type = "boolean", default = false},
	})

	return export.link({
		lang = frame.args[1] and require'Module:languages'.getByCode(frame.args[1]),
		lemma = args[1],
		kana = args[2],
		gloss = args[3],
		lit = args["lit"],
		pos = args["pos"],
		id = args["id"],
		linkto = args["linkto"],
		tr = args["rom"],
	}, {
		caps = args["caps"],
		hist = args["hist"],
		disableSelfLink = args["self"],
	})
end

return export