-- Çavkanî: fr.wiktionary.org [[Module:traduction]]
b = require('Modul:bingeh')
m_languages = require("Module:ziman")
local m_links = require("Module:links")

local export = {}

local cats = {}
-- Activer pour voir les catégories générées
-- Seulement pour déboguer avec l'aperçu : désactiver en sauvegardant
local isdebug = false

function _categorie_section(nom_cat, clef, ecrit)
    if isdebug then
    	if clef then
        	return b.bike_kategori(nom_cat, nil, true) .. '(' .. clef .. ')'
        else
        	return b.bike_kategori(nom_cat, nil, true)
        end
    else
        return b.bike_kategori_naverok(nom_cat, clef, ecrit)
    end
end

function _fait_span_trad(texte, code)
    if (texte ~= nil and code ~= nil) then
        return '<span class="trad-' .. code .. '">' .. texte .. '</span>'
    else
        return ''
    end
end

-- Fonction pour écrire l'équivalent du modèle Z
function export.Z(frame)
    -- Récupération des variables nécessaires à la création du titre
    local args = frame:getParent().args
    args = b.trim_parametres(args)
    local code  = args[1]
    local trier = false
    if (args[2] == 'trier') then trier = true end
    local article = mw.title.getCurrentTitle()
    
    -- Pas de code de langue, indispensable
    if code == nil or code == '' then
    	table.insert(cats, _categorie_section('Wîkîferheng:Wergerên Z bi koda ziman a nediyarkirî'))
        return '<i><font color="red">Navê zimanî nehatiye nivîsîn</font></i>[[Wîkîferheng:Lîsteya zimanan|*]]' .. table.concat(cats)
    end
    
    -- A-t-on une langue correspondant au code ?
   	local lang = m_languages.getByCode(code, 1, "allow etym", "allow family")
	local langue = lang:getCanonicalName()
    local textet = {}
    
    -- Oui : écrit le texte
    if (langue ~= nil and langue ~= '') then
        table.insert(textet, b.ucfirst(langue))
        
        -- Catégories
        local newcattext = trier and 'Wîkîferheng:Traductions à trier en ' or 'Werger bi '
        table.insert(cats, _categorie_section(newcattext .. langue))
    
    -- Langue sans code! Catégorisée pour la retrouver
    else
        table.insert(textet, '<i><font color="red">' .. code .. '</font></i>[[Modul:ziman|*]]')
        
        table.insert(cats, _categorie_section('Wîkîferheng:Wergerên Z bi koda ziman a nediyarkirî', code))
    end
    
    texte = _fait_span_trad(table.concat(textet), code)
    
    return texte .. table.concat(cats)
end

---------------------------------------------------------------------------------------------------------
-- Modul bo şablonên {{W}}, {{W+}} û {{W-}}
-- {{W|koda zimanê|peyv|zayend|jimar|tr=transliterasyon|cuda=|guman=}}

-- kod, peyv, zayend, jimar, tr (an R), cuda, guman
local interwiki_langs = {
	["kmr"] = "ku",
	["nds-de"] = "nds",
	["nds-nl"] = "nds",
	["pdt"] = "nds",
	["zza"] = "diq",
	["kiu"] = "diq",
}

local ignore_caps = {
	["ko"] = true,
}

local tracked = {
	["se"] = true,
}

-- The main entry point.
-- This is the only function that can be invoked from a template.
function export.W(frame)
	local params = {
		[1] = {required = true, default = "und"},
		[2] = {},
		[3] = {list = true},
		["guman"] = {},
		["cuda"] = {},
		["alt"] = {alias_of = "cuda"},
		["dif"] = {alias_of = "cuda"},
		["id"] = {},
		["sc"] = {},
		["tr"] = {},
		["ts"] = {},
		["R"] = {alias_of = "tr"},
		["lit"] = {},
		["xs"] = {}, --parametre tê bikaranîn lê tiştek nake. 
		}
	
	local args = require("Module:parameters").process(frame:getParent().args, params)
	
	local terminfo = {
		lang = require("Module:languages").getByCode(args[1]) or require("Module:languages").err(args[1], 1),
		sc = (args["sc"] and (require("Module:scripts").getByCode(args["sc"]) or error("The script code \"" .. args["sc"] .. "\" is not valid.")) or nil),
		term = args[2] or (mw.title.getCurrentTitle().nsText == "Template" and "term") or nil,
		alt = args["cuda"],
		id = args["id"],
		genders = args[3],
		tr = args["tr"],
		ts = args["ts"] or args["R"],
		lit = args["lit"],
		interwiki = frame.args["interwiki"],
		}
		
	if (frame:getParent().args["guman"] == 'erê') then
		guman = '<sup style="font-size:90%" title="Gumanek ser vê wergerê heye"><b><i>?</i></b></sup>'
		guman = guman .. b.bike_kategori_naverok("Kontrola wergerê")
	else
       	guman =''
	end

	return guman .. export.show_terminfo(terminfo)
end

function export.show_terminfo(terminfo, no_check_redundant_translit)
	-- Translations must be for mainspace languages
	if terminfo.lang:getType() == "reconstructed" or terminfo.lang:getType() == "appendix-constructed" then
		error("Translations must be for attested and approved main-namespace languages.")
	end
	
	-- Don't show the interwiki link if there is nothing to link to.
	if terminfo.term then
		-- Track translations for particular languages
		if tracked[terminfo.lang:getCode()] then
			require("Module:debug").track("translations/" .. terminfo.lang:getCode())
		end
		
		local wmlangs = {}
		
		if interwiki_langs[terminfo.lang:getCode()] then
			wmlangs = {require("Module:wikimedia languages").getByCode(interwiki_langs[terminfo.lang:getCode()])}
		else
			wmlangs = terminfo.lang:getWikimediaLanguages()
		end
		
		-- Don't show the interwiki link if the language is not recognised by Wikimedia
		-- or if the term contains links (for SOP translations)
		if terminfo.term:find("[[", nil, true) or #wmlangs == 0 then
			terminfo.interwiki = false
		end
		
		if wmlangs[1] and ignore_caps[wmlangs[1]:getCode()] then
			terminfo.term2 = mw.ustring.gsub(terminfo.term, "^%^", "")
		end
		
		if (terminfo.interwiki == "tpos") then
			terminfo.interwiki =
				"<span style=\"vertical-align:20%; font-size:80%;\" class=\"" .. terminfo.interwiki .. "\">&nbsp;[[:" ..
				wmlangs[1]:getCode() .. ":" ..
				terminfo.lang:makeEntryName(terminfo.term2 or terminfo.term) ..
				"|→&nbsp;" .. wmlangs[1]:getCode() .. "]]</span>"
		elseif (terminfo.interwiki == "tneg") then
			terminfo.interwiki = ''
		elseif (terminfo.interwiki ~= false) then
			terminfo.interwiki =
				"<span style=\"vertical-align:20%; font-size:80%;\">&nbsp;[[:" ..
				wmlangs[1]:getCode() .. ":" ..
				terminfo.lang:makeEntryName(terminfo.term2 or terminfo.term) ..
				"|<span style=\"color:gray;\">→&nbsp;" .. wmlangs[1]:getCode() .. "</span>]]</span>"
		end
	else
		-- Track what entries currently don't provide a term
		require("Module:debug").track("translations/no term")
		require("Module:debug").track("translations/no term/" .. terminfo.lang:getCode())
	end
	
	-- languages needing superscripts in tr
	need_super = {
		["yue"] = true, ["gan"] = true, ["hak"] = true,
		["cjy"] = true, ["nan"] = true, ["hsn"] = true,
	}
	
	if terminfo.lang and need_super[terminfo.lang:getCode()] and terminfo.tr then
		terminfo.tr = mw.ustring.gsub(terminfo.tr, '([1-9]%-?[1-9]?)','<sup>%1</sup>')
	end
	
	return m_links.full_link(terminfo, "translation", true, no_check_redundant_translit)
end

return export