Modulo che implementa il template {{Codice statistico}}.


--[[
* Modulo che implementa il template Codice statistico.
]]--

require('Modulo:No globals')

local getArgs = require('Modulo:Arguments').getArgs
local mWikidata = require('Modulo:Wikidata')

local p = {}

local function formatP439(id)
	local formatted_id = string.gsub(id, "(%d%d)(%d)(%d%d)(%d%d%d)", "%1 %2 %3 %4")
	return string.format('[http://www.statistik-portal.de/Statistik-Portal/gemeindeverz.asp?G=%s %s]', id, formatted_id)
end

local function formatP964(id)
	local formatted_id = string.gsub(id, "(%d)(%d%d)(%d%d)", "%1 %2 %3")
	return string.format('[http://www.statistik.at/blickgem/gemDetail.do?gemnr=%s %s]', id, formatted_id)
end

local codes = {
	AUT = { prop = 'P964', catprefix = 'Codice municipale austriaco', format = formatP964 },
	CHE = { prop = 'P771', catprefix = 'Codice OFS' },
	DEU = { prop = 'P439', catprefix = 'Codice municipale tedesco', format = formatP439 },
	ESP = { prop = 'P772', catprefix = 'Codice INE' },
	FRA = { prop = 'P374', catprefix = 'Codice INSEE' },
	ITA = { prop = 'P635', catprefix = 'Codice ISTAT' }
}

local function getWikidataCategory(userval, wdval, code)
	local cat
	if userval then
		userval = string.gsub(userval, ' ', '')
		if not wdval then
			cat = string.format('%s assente su Wikidata', code.catprefix)
		elseif wdval == userval and code.catuguali then
			cat = string.format('%s uguale Wikidata', code.catprefix)
		else
			cat = string.format('%s differente Wikidata', code.catprefix)
		end
	elseif wdval then
		cat = string.format('%s letto da Wikidata', code.catprefix)
	end
	return cat and string.format('[[Categoria:%s]]', cat) or ''
end

-- Per l'utilizzo da altro modulo
function p._main(args)
	local code, userval, wdval, formatted_userval, formatted_wdval
	local cat = ''

	-- valore utente
	userval = args[1]

	-- ricerca paese
	if args.iso3166 then
		code = codes[args.iso3166]
	end
	if not code then
		local iso3166 = mWikidata._getProperty({ 'P17', showprop = 'P298', from = args.from, n = 1 }) or {}
		code = codes[iso3166]
	end

	-- valore letto da Wikidata	
	if code then
		wdval = mWikidata._getProperty({ code.prop, from = args.from, n = 1 }) or {}
		formatted_wdval = (wdval and code.format) and code.format(wdval) or wdval
		formatted_userval = (userval and code.format) and code.format(string.gsub(userval, ' ', '')) or userval
	end

	-- categoria di servizio
	if mw.title.getCurrentTitle().namespace == 0 and (userval or wdval) then
		cat = getWikidataCategory(userval, wdval, code)
	end

	return (formatted_userval or formatted_wdval or '') .. cat
end

-- Entry-point per il template {{Codice statistico}}
function p.main(frame)
	return p._main(getArgs(frame, {parentOnly = true}))
end

return p