local export = {}

local lang
-- This is based on the function in [[Module:translations/multi]].
local function get_args(template_content)
	local args = {}
	local i = 0
	
	for arg in mw.text.gsplit(template_content, "¦", true) do
		local name, value = arg:match("^(.-)=(.-)$")
		if name then
			if value ~= "" then
				name = tonumber(name) or name
				args[name] = value
			end
		elseif arg == "" then
			i = i + 1
			args[i] = nil
		else
			i = i + 1
			args[i] = arg
		end
	end
	
	return args
end

local script_data = mw.loadData "Module:scripts/data"
local kana = script_data.Kana.characters .. script_data.Hira.characters
local kana_pattern = "^[" .. kana .. "%W]+$"
local function is_kana(str)
	return mw.ustring.find(str, kana_pattern) ~= nil
end

local ja_link = require "Module:ja-link".link
local function process_ja_r_template(template_content)
	local args = get_args(template_content)
	
	-- This logic is copied from [[Module:ja-link]].
	local kana = args[2]
	if not kana then
		kana = args[1]
		if not (kana and is_kana(kana)) then
			-- error
		end
	end
	
	local data = {
		lang = lang,
		lemma = args[1],
		kana = kana,
		gloss = args[3],
		lit = args["lit"],
		pos = args["pos"],
		linkto = args["linkto"],
		transliteration = args["rom"],
	}
	
	local options = {
		caps = args["caps"],
		hist = args["hist"],
	}
	
	return ja_link(data, options)
end

function export.main(frame)
	lang = require("Module:languages").getByCode(frame.args[1] or "ja")
	local lang_code = lang:getCode()
	local wikicode = frame:getParent().args["data"]
	
	if not wikicode then
		return ""
	else
		local result = (mw.ustring.gsub(wikicode, "⦃⦃" .. lang_code .. "%-r¦([^⦃⦄]+)⦄⦄", process_ja_r_template))
		return result
	end
end

return export