La documentazione per questo modulo può essere creata in Modulo:Autore2/man

local item = mw.wikibase.getEntity()
local lang = mw.language.getContentLanguage()
local p = {}
local outputText = ''
local outputCat = ''

function add(str)
	outputText = outputText..str
end

function addCatLink(name, label)
	label = label or name
	outputText = outputText .. '[[:Category:' .. mw.text.trim(name) .. '|' .. label .. ']]'
end

function addCat(name, label)
	label = label or name
	outputCat = outputCat .. '[[Category:' .. mw.text.trim(name) ..  '|' .. label .. ']]'
end

function getFirstNameLastName(fullName)
	firstName = item:formatPropertyValues('P735').value
	lastName = item:formatPropertyValues('P734').value
	
	if not string.find(fullName, firstName) then
		firstName = ''
	end
	if not string.find(fullName, lastName) then
		lastName = ''
	end
	
	if firstName == '' and lastName ~= '' then
		firstName = fullName:gsub(' ' .. lastName, '')
	end
	
	if firstName ~= '' and lastName == '' then
		lastName = fullName:gsub(firstName .. ' ', '')
	end
	
	if firstName == '' and lastName == '' then
		sp = fullName:find(' ')
		if sp then
			firstName = fullName:sub(0, sp)
			lastName = fullName:sub(sp+1)
		else
			firstName = fullName
		end
	end
	
	return firstName, lastName
end

function getImage(property)
	images = item.claims and item.claims[property]
	if images and #images >= 1 and  images[1].mainsnak.datavalue then
		return images[1].mainsnak.datavalue.value
	end
end

--converte il numero dato a numero romano
function toRoman(num)
    local t = {
        {1000, "M"},
        {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"},
        {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"},
        {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"} 
    }
    local ret = {}
    for _, v in ipairs(t) do
        local val, letter = unpack(v)
        while num >= val do
            num = num - val
            table.insert(ret, letter)
        end
    end
    return table.concat(ret), num
end

function parseDate(value)
	year, month, day = value.time:match( '.+(%d?%d%d%d%d)%-(%d%d)%-(%d%d).+' )
	century = math.ceil(year / 100)
	return century, year, month, day
end

function formatDate(value)
	if value and value.time then
		century, year, month, day = parseDate(value)
		
		if value.precision == 7 or value.precision == 8 then
			return toRoman(century) .. ' secolo'
		elseif value.precision == 9 then
			return year
		elseif value.precision == 10 then
			return mw.getLanguage('vec'):formatDate('F Y', year .. '-' .. month .. '-' .. 1) 
		elseif value.precision == 11 then
			return mw.getLanguage('vec'):formatDate('j F Y', year .. '-' .. month .. '-' .. day) 
		end
	end
	return '...'
end

function extractValues(values)
	local list = {}
	for j, k in pairs(values or {}) do
		if  k.mainsnak.datavalue then
			if  k.mainsnak.datavalue.type == 'wikibase-entityid' then
				table.insert(list, mw.wikibase.label('Q' .. k.mainsnak.datavalue.value["numeric-id"]))
			else
				table.insert(list, k.mainsnak.datavalue.value)
			end
		end
	end
	return list
end

function formatDates(values)
	local list = {}
	for j, k in pairs(values or {}) do
		if k.mainsnak.datavalue then
			s = formatDate(k.mainsnak.datavalue.value)
			if k.qualifiers and k.qualifiers['P1480'] then
				s = mw.wikibase.label('Q' .. k.qualifiers['P1480'][1].datavalue.value["numeric-id"]) .. ' ' .. s
			end
			table.insert(list, s)
		end
	end
	return list
end

function getCenturies(birthValues, deathValues, floruitValues)
	local earliest, latest
	for j, k in pairs(birthValues or {}) do
		if k.mainsnak.datavalue then
			century, year, month, day = parseDate(k.mainsnak.datavalue.value)
			if not earliest or earliest > century then
				earliest = century
			end
		end
	end

	for j, k in pairs(deathValues or {}) do
		if k.mainsnak.datavalue then
			century, year, month, day = parseDate(k.mainsnak.datavalue.value)
			if not latest or latest < century then
				latest = century
			end
		end
	end

	list = {}

	if not earliest and not latest then
		for j, k in pairs(floruitValues or {}) do
			century, year, month, day = parseDate(k.mainsnak.datavalue.value)
			table.insert(list, century)
		end
	else
		table.insert(list, earliest)
		if earliest ~= latest then
			table.insert(list, latest)
		end
	end
	return list
end

--gather all data from the WD item
function p.getData(authorItem)
	item = authorItem or item
	
	local data = {}
	
	data.isPerson = item.claims['P31'][1].mainsnak.datavalue.value['numeric-id'] == 5
	
	data.pagename = mw.title.getCurrentTitle().text
	data.fullName = item:getLabel() or data.pagename
	if item.descriptions and item.descriptions.vec then
		data.description = item.descriptions.vec.value
	end
	data.firstName, data.lastName = getFirstNameLastName(data.fullName)
	data.sortingKey = data.firstName
	if data.lastName ~= '' then
		data.sortingKey = data.lastName .. ', ' .. data.firstName
	end
	
	data.birthName = item:formatPropertyValues('P1477').value
	data.sex = (item:formatPropertyValues('P21').value == 'femmina' and 'female') or 'male'
	
	pseudonymList = {}
	allPseudonym = extractValues(item:getBestStatements('P742'))
	for j, k in pairs(allPseudonym) do
		if k ~= data.fullName then
			table.insert(pseudonymList, k)
		end
	end
	if item.aliases and item.aliases.vec then
		for j, k in pairs(item.aliases.vec) do
			if k ~= data.fullName then
				local alreadyPresent = false
				for l, m in pairs(pseudonymList) do
			        if m == k.value then 
			        	alreadyPresent = true
			        end
			    end
			    
			    if not alreadyPresent then
					table.insert(pseudonymList, k.value)
				end
			end
		end
	end
	data.pseudonym = mw.text.listToText(pseudonymList, " '''o''' ", " '''o''' ")

	data.birthPlace = mw.text.listToText(extractValues(item:getBestStatements('P19')), ' o ', ' o ')
	data.deathPlace = mw.text.listToText(extractValues(item:getBestStatements('P20')), ' o ', ' o ')
	
	birthValues = item:getBestStatements('P569')
	deathValues = item:getBestStatements('P570')
	floruitValues = item:getBestStatements('P1317')
	data.birthDate = mw.text.listToText(formatDates(birthValues), ' o ', ' o ')
	data.deathDate = mw.text.listToText(formatDates(deathValues), ' o ', ' o ')
	data.centuries = getCenturies(birthValues, deathValues, floruitValues)
	
	data.image = getImage('P18')
	data.flagImage = getImage('P41')
	
	data.vecwikipediaLink = item:getSitelink('vecwiki')
	data.itwikipediaLink = item:getSitelink('itwiki')
	data.itwikisourceLink = item:getSitelink('itwikisource')
	data.wikiquoteLink = item:getSitelink('itwikiquote')
	data.commonsLink = item:getSitelink('commons')
	
	return data
end

--build the output
function p.autor(frame)
	if frame == nil or frame:getParent() == nil then
		error('Nessun frame rilevato')
	end
	
	if not item then
		return mw.getCurrentFrame():expandTemplate{title = 'No Wikidata'} .. "\n'''" .. mw.title.getCurrentTitle().text .. "'''.\n==Testi==\n[[Categoria:Pagina mia tacà con Wikidata]]"
	end
	
	local localDescription = frame:getParent().args[1]
	
	local data = p.getData()
	local numTexts = mw.site.stats.pagesInCategory('Testi de ' .. data.pagename, 'pages')
	local numCitations = mw.site.stats.pagesInCategory('Testi in cui xe cità ' .. data.pagename, 'pages')
	
	--IMAGE
	if data.image or data.flagImage then
		add('[[File:' .. (data.image or data.flagImage) .. '|thumb|' .. data.fullName .. ']]')
	end
	
	--START TEXT
	add("'''" .. data.fullName .. "'''")
	
	if data.isPerson then
		add(' (')
		if data.birthPlace and data.birthPlace ~= '' then
			add(data.birthPlace .. ', ')
		end
		if data.birthDate and data.birthDate ~= '' then
			add(data.birthDate)
		else
			add('...')
		end
	
		add(' - ')
		
		if data.deathPlace and data.deathPlace ~= '' then
			add(data.deathPlace .. ', ')
		end
		if data.deathDate and data.deathDate ~= '' then
			add(data.deathDate)
		else
			add('...')
		end
		add(')')
		
		if data.birthName and data.birthName ~= '' and data.birthName ~= data.fullName then
			add(", " .. lang:gender(data.sex, "nato", "nata") .. " '''" .. data.birthName .. "'''")
		end
		
		if data.pseudonym and data.pseudonym ~= '' then
			add(", " .. lang:gender(data.sex, "dito", "dita") .. " anca '''" .. data.pseudonym .. "'''")
		end
	end
	
	if data.description then
		add(', ' .. data.description)
		if localDescription then
			add(', ' .. localDescription)
		end
		add('.')
	end
	
	
	if data.vecwikipediaLink or data.itwikipediaLink then
		add('<div style="margin:5px;">')
		add("[[File:Wikipedia-logo.png|20px]] ''Vose su '''[[:w:" .. (data.vecwikipediaLink or ('it:' .. data.itwikipediaLink)) .. "|Wikipedia]]'''''</div>")
	end
	
	if data.wikiquoteLink then
		add('<div style="margin:5px;">')
		add("[[File:Wikiquote-logo.svg|20px]] ''Citazion su '''[[:q:it:" .. data.wikiquoteLink .. "|Wikiquote]]'''''</div>")
	end
	
	if data.commonsLink then
		add('<div style="margin:5px;">')
		add("[[File:Commons-logo.svg|20px]] ''Imagini, video e audio su  '''[[:commons:" .. data.commonsLink .. "|Commons]]'''''</div>")
	end
	
	if numTexts > 0 then
		add('\n<div style="margin:5px;">')
		add("[[File:Logo book2.png|20px]] ''Elenco alfabetico de tuti i '''[[:Categoria:Testi de " .. data.pagename .. "|testi de " .. data.fullName .. "]]''' ")
		add("(" .. numTexts .. ' ' .. lang:convertPlural(numTexts, 'testo', 'testi') .. ")''</div>")
	end
	
	if numCitations > 0 then
		add('\n<div style="margin:5px;">')
		add("[[File:Logo book2.png|20px]] '''''[[:Categoria:Testi in cui xe cità " .. data.pagename .. "|Testi in cui xe cità " .. data.fullName .. "]]''' ")
		add("(" .. numCitations .. ' ' .. lang:convertPlural(numCitations, 'testo', 'testi') .. ")''</div>")
	end
	
	add('\n\n==Testi==\n')
	
	--CATEGORIES
	
	addCat('Autori', data.sortingKey)
	
	for j, k in pairs(data.centuries) do
		addCat('Autori del ' .. toRoman(k) .. ' secolo', data.sortingKey)
	end
	
	if data.itwikipediaLink then
		addCat('Autori presenti su it.wiki', data.sortingKey)
	end
	
	if data.itwikisourceLink then
		addCat('Autori presenti su it.ws', data.sortingKey)
	end
	
	return outputText .. outputCat
end

return p