Moduuli:Fr:Conversion

Wikipediasta
Siirry navigaatioon Siirry hakuun

local math_mod = require "Module:Fr:Math"
local formatnum = require "Module:Fr:Format".do_formatnum
local params = require "Module:Fr:Conversion/Données"
local defaultlang = 'fr'

local p = {}

local i18n = {
	invalidunitcat = 'Page with an unsupported measurement unit',
	invalidsourceunit = '$1 (unité non supportée)',
	invalidtargetunit = 'unité cible non supportée $1',
	typemismatch = 'impossible de convertir $1 en $2'
}

local function numString(val, rounding, displayformat) -- transforme un nombre en chaîne
	if rounding then
		val = math_mod._round( val, rounding )
	end
	
	-- print number with rounding precision
	rounding=tonumber(rounding)
	if rounding and rounding > 0 then
		val = string.format("%."..rounding.."f", val)
		-- print number with current locale
		val = mw.getCurrentFrame():preprocess('{{formatnum:' .. val ..'}}') 
	else
		val = formatnum({tostring(val)}) 
	end

	if displayformat and displayformat.suffix then
		val = val .. suffix
	end
	return val
end

local function convert(value, sourceunitdata, targetunitdata) -- convertir une valeur numérique en son équivalent dans une autre unité de mesure
	if not value then
		return nil
	end
	if type(value) ~= 'number' then
		return error("bad datatype: " .. type(value))
	end
	if (not sourceunitdata) or (not targetunitdata) then
		return value
	end
	return value * sourceunitdata[2] / targetunitdata[2]
end

function p.displayvalue(val, sourceunit, displayformat, errhandling) -- affiche une valeur formatée)
	
	-- préparation des paramètres
	local numval = tonumber(val)
	if not numval then -- si les données sont inhabituelles, on laisse la fonction appelante se débrouiller
		return val
	end
	
	if not displayformat or type(displayformat) ~= 'table' then
		displayformat = {}
	end
	local showunit, showlink, targetunit = displayformat.showunit, displayformat.showlink, displayformat.targetunit
	
	local rounding_temp_val=tostring(val)
	local default_rounding=0
	
	-- Default precision is same than input precision
	local pos=string.find(rounding_temp_val, "%.")
	if pos then 
		default_rounding=string.len(string.sub(rounding_temp_val, pos+1))
	end
	
	local rounding = tonumber(displayformat.rounding or default_rounding)
	
	-- récupération des donnnées concernant les unités
	if sourceunit and not targetunit then
		targetunit = sourceunit
	end
	local sourceunitdata, targetunitdata = sourceunit, targetunit
	if type(sourceunitdata) ~= 'table' then
		sourceunitdata = params.units[sourceunit] or params.units[params.redirects[sourceunit]]
	end
	if type(targetunitdata) ~= 'table' then	
		targetunitdata = params.units[targetunit] or params.units[params.redirects[targetunit]]
	end

	local maintenancestr = ""	

	
	-- conversion

	local function invalidsourcefallback(val, sourceunit) -- text to be shown when source unit is not supported
		local str = tostring(val)
		if sourceunit:match('Q%d+') or sourceunit:match('q%d+') then -- wikidata item
			sourceunit = mw.wikibase.label(sourceunit)
		end
		return val .. ' ' .. i18n['invalidsourceunit']:gsub('$1', sourceunit) .. '[[Category:' .. i18n.invalidunitcat .. '|' .. sourceunit .. ']]'
	end


	-- escape if source unit is invalid
	if (sourceunit and targetunit) and (targetunit~= sourceunit) and (not sourceunitdata or not sourceunitdata[1]) then
		return invalidsourcefallback(val, sourceunit)
	end

	if sourceunit and (not sourceunitdata) then 
		local label = sourceunit
		local item = sourceunit:match('q%d+') or sourceunit:match('Q%d+')
		local link
		local symbol
		if item then
			label = mw.wikibase.label(item)
			link = mw.wikibase.sitelink(item)
			if (displayformat.showunit) and (displayformat.showunit ~= 'long') then -- symbole retrieved only if needed (somewhat expensive)
				symbol = mw.wikibase.getEntityObject(item):formatPropertyValues( 'P558' )
				if symbol then
					symbol = symbol.value
				end
			end
		end
		sourceunitdata = {nil, 1, symbol or label, item, link, label, label}
		targetunit, targetunitdata  = sourceunit, sourceunitdata 
	end
	
	-- warn if targetunit is unknown
	if targetunit and (not targetunitdata) then
		targetunit, targetunitdata = sourceunit, sourceunitdata
		maintenancestr = maintenancestr .. " "  .. i18n['invalidtargetunit']:gsub('$1', targetunit) .. '[[Category:' .. i18n.invalidunitcat .. '|' .. targetunit .. ']]'
	end

	-- check for type mismatch
	if (sourceunitdata and targetunitdata) and (targetunitdata[1] ~= sourceunitdata[1]) then
		local errmsg = i18n.typemismatch
		errmsg = errmsg:gsub('$1', sourceunit)
		errmsg = errmsg:gsub('$2', targetunit)
		maintenancestr = maintenancestr .. '(' .. errmsg .. ')'
		targetunit, targetunitdata = sourceunit, sourceunitdata
	end

	-- convert if needed
	if (sourceunit and targetunit) and (sourceunit ~= targetunit) then
		numval = convert(numval, sourceunitdata, targetunitdata)

	-- if no conversion then do not unnaturally expand precision 
	elseif rounding > default_rounding then
		rounding=default_rounding	
	end

	if displayformat.raw == true then -- nombre non formaté chaîne convertible en nombre sauf si catégorie de maintenance
		return (tostring(numval) or "") .. maintenancestr
	end

	local numstr = numString(numval, rounding)

	-- affichage de l'unité
	local unitstr, link
	if not targetunitdata then -- pour éviter les bugs
		targetunitdata = {}
	end
	if showunit == 'long' then -- format long = montrer l'unité en entier
		if (numval or 0) > 1 then
			unitstr = targetunitdata[7]
		else
			unitstr = targetunitdata[6]
		end
	elseif showunit and (showunit ~= '-') then
		unitstr = targetunitdata[3]
	end

	-- showlink
	if type( displayformat.showlink == 'string') then --liens personnalisés
		link = displayformat.showlink
	elseif displayformat.showlink == true then -- liens vers l'article dédié
		link =  targetunitdata[5]
	end 
	if unitstr and link then
		unitstr = '[[' .. link .. '|' .. unitstr .. ']]'
	end

	return numstr .. ' ' .. (unitstr or '') .. maintenancestr
end

function p.display(frame)
	local args = frame.args
	local value, origunit, targetunit = args[1], args[2], args[3]
	local rounding = args.rounding
	local showlink, showunit = 	args.showlink, args.showunit
	if showunit == 'true' then
		showunit = true
	end
	if showlink == 'true' then
		showlink = true
	end
	displayformat = {showunit = showunit, showlink = showlink, rounding = rounding, targetunit = targetunit}
	return p.displayvalue(value, origunit, displayformat)
end
return p