local export = {}

local debug_force_cat = false -- set to true for testing

local m_affix = require("Module:affix")

local pseudo_loan_by_source = {
	["ar"] = "阿拉伯語",
	["de"] = "德語",
	["en"] = "英語",
	["es"] = "西班牙語",
	["fr"] = "法語",
	["it"] = "意大利語",
	["ja"] = "日語",
	["la"] = "拉丁語",
}

local function get_pseudo_loan_text(lang, source, has_parts, nocap)
	local langcode = lang:getCode()
	local sourcecode = source:getCode()
	local function glossary_pseudo_loan_link(display)
		return "[[Appendix:Glossary#pseudo-loan|" .. display .. "]]"
	end
	local text
	if langcode == "ja" and sourcecode == "en" then
		text = "{{m|ja|和製英語}}," ..
			glossary_pseudo_loan_link("偽英語") .. ")"
		text = mw.getCurrentFrame():preprocess(text)
	elseif pseudo_loan_by_source[sourcecode] then
		text = "偽" .. pseudo_loan_by_source[sourcecode]
	else
		text = "偽" .. source:getCanonicalName()
	end
	if has_parts then
		text = text .. ",源自"
	end
	return text
end


function export.show_pseudo_loan(data)
	local parts_formatted = {}
	local categories = {}

	if not nocat then
		table.insert(categories, "源自" .. data.source:getCanonicalName() .. "的偽借詞")
		table.insert(categories, "派生自" .. data.source:getCanonicalName() .. "的詞")
	end

	-- Make links out of all the parts
	for i, part in ipairs(data.parts) do
		part.part_lang = part.lang
		-- When the part is in the source language, we need to use `source` so the part gets linked correctly. Otherwise,
		-- `data.lang` will be used, which is correct, because the value is used as the destination language in
		-- derived-from categories. An example is [[Ego-Shooter]], a German pseudo-loan from English but where the
		-- first part is from Latin.
		part.lang = part.lang or data.source
		part.sc = part.sc or data.sc
		table.insert(parts_formatted, m_affix.link_term(part, data))
	end

	local text_sections = {}
	if not data.notext then
		table.insert(text_sections, get_pseudo_loan_text(data.lang, data.source, #data.parts > 0, data.nocap))
	end
	table.insert(text_sections, m_affix.join_formatted_parts {
		data = data, parts_formatted = parts_formatted, categories = categories}
	)
	return table.concat(text_sections)
end


return export