Módulo:Country data

Permanently protected module
Origem: Wikipédia, a enciclopédia livre.
Documentação do módulo[ver] [editar] [histórico] [purgar]


Descrição

Este módulo tem funções de informação países.

Uso

Outra documentação:

--[[
This module is intended to replace the functionality of {{bandeira2}} and related
templates.  It provides several methods, including
]]

local p = {};

local gdata = mw.loadData ("Módulo:Country data/lista" )
local dates = require "Módulo:Data complexa"
local linguistic = require "Módulo:Linguística"

local function _getCompetition(c,aaaa)
    local gdomain = mw.loadData ( "Módulo:Bandeira/Domínio" ) -- carregado apenas nos itens em que serve, leva um pouco de espaço
   
    local symbs = {
        ['cm'] = "na copa do mundo",
        ['copadomundo'] = "na copa do mundo",
        ['ce'] = "no Campeonato Europeu",
        ['euro'] = "no Campeonato Europeu",
        ['chm'] = "no Campeonato Mundial",
        ['can'] = "na copa das confederações",
        ['copadasconfederacoes'] = "na copa das confederações",
        ['en'] = "en",
        ['jo'] = "nas Olimpíadas",
        ['jp'] = "nos Jogos Paralímpicos",
    }

    local str = symbs[string.lower(c or '')] or ""
   
    --edition
    if(aaaa ~= nil and aaaa ~= "") then
        if(c=="jo"  or c=="jp" ) then
            local o=gdomain.jo["_"..aaaa];
            if(o ~= nil) then
                str = str .." "..o
            end
        else
           str = str .." "..aaaa
        end
    end

    return str
end

local function printFlag(flagfile, alt, displayformat)
   
    displayformat = displayformat or {}
    local size = displayformat.size or '20x15'
    local border = 'border|'
   
    if displayformat.border == '-' then
        border = ''
    end
   
    if not alt then
        alt = ''
    end
    return '<span class="flagicon">' ..
            '[[Ficheiro:' .. flagfile .. '|' .. size ..'px|' .. border  .. alt ..'|class=noviewer]]' ..
            '</span>';
end

local function bestfordate(data, period) -- data contém uma tabela cujas chaves são datas no formato ['2010'] = ou ['2010-05-04'] =
    if type(data) == 'string' then
        return data
    end

    -- muito artesanal, para melhorar
    if (not period) or (period == 'default') then
        return data.default
    end
   
    local val = data.default
    local bestdate = '-1000-01-01'
    for i, j in pairs(data) do
        if j ~= 'default' and dates.before(period, i) and dates.before(i, bestdate) then -- se o valor for mais recente que o período menos recente do que o melhor encontrado
            val = j
            bestdate = i
        end
    end
    return val
end


local function valueAtDate(data, period, topic) -- tópico: tipo de bandeira, gênero do adjetivo, etc.
    if type(data) == 'string' or type(data) == 'nil' then
        return data
    end
    if type(data) ~= 'table' then
        return error('bad datatabpe ' .. type(data))
    end
    topic = topic or "default"
    if data[topic] then
        return bestfordate(data[topic], period)
    else
        return bestfordate(data, period)
    end
    return error()
end

local function getData(datatable, typedata, topic, period) -- recupera a cadeia de caracteres mais apropriada na tabela de dados
    -- datatable: a tabela de submódulos, por exemplo [[Módulo:Country data/granada]]
    -- typedata: "flag" / "name" / "adjetivo"
    -- period: data in ISO format
    -- topic: for instance "navy" for naval ensign
    local val = datatable[typedata]

    if not val then -- error handling ?
        return nil
    end

    local val = valueAtDate(val, period, topic)

    if type(val) ~= 'string' then -- error handling ?
        return error(val)
    end
    return val
end

local function getAdjetivo(data, gender, number)
    if not gender then
        gender = 'm'
    end
    if not number then
        number = 's'
    end
    if (gender ~= 'm' and gender ~= 'f') then
        return error('genêro deve ser m ou f é ' .. gender)
    end
    if (number ~= 's' and number ~= 'p') then
        return error('número deve s ou p é ' .. number)
    end
    return getData(data, 'adjetivo', (gender .. number))
end

local function getDemonym (data, gender, number)
    if data.demonym == nil then
        return linguistic.ucfirst( getAdjetivo(data, gender, number) )
    end
    gender = gender or 'm'
    number = number or 's'
    if (gender ~= 'm' and gender ~= 'f') then
        return error('genêro deve ser m ou f é ' .. gender)
    end
    if (number ~= 's' and number ~= 'p') then
        return error('número deve ser s ou p é ' .. number)
    end
    return getData(data, 'demonym', (gender .. number))
end

local function getLabel(data, topic, period, form)
    local label
    if (not form) or form == 'short' then
        label = getData(data, 'shortname', topic, period)
    end
    if not label then
        label = getData(data, 'name')
    end
    if (not label) and data.item then
        label = mw.wikibase.label(getData(data, 'item'))
    end
    return label
end

local function getLink(data, topic, period)
    local link = getData(data, 'link', topic, period)
    if (not link) and data.item then
        link =  mw.wikibase.label(getData(data, 'item'))
    end
    return link
end

local function applyregex(str, areadata)
    local cio = 'cõdigo CIO (esperando)' --require('Módulo:Wikidata')._formatStatements({entity= areadata.item, property= 'P984'}) or '??'

    local label = getData(areadata, 'name')
    local of = linguistic.of(label, areadata.genre)
   
    str = mw.ustring.gsub(str, '$de$label', of)
    str = mw.ustring.gsub(str, '$label', label)
    str = mw.ustring.gsub(str, '$cio', 'cio')

    if string.find(str, '$gentile') then
        local function get(genre) return getData(areadata, 'adjetivo', genre) end
        local gentileMS, gentileFS, gentileMP, gentileFP = get('ms'), get('fs'), get('mp'), get('fp')
        str = mw.ustring.gsub(str, '$gentileMS', gentileMS)
        str = mw.ustring.gsub(str, '$gentileFS', gentileFS)
        str = mw.ustring.gsub(str, '$gentileMP', gentileMP)
        str = mw.ustring.gsub(str, '$gentileFP', gentileFP)
    end
    return str
end

local function getDatatable(zone)
    zone = mw.ustring.lower(zone)
    if gdata[zone] then
        return require('Módulo:Country data/' .. gdata[zone])
    else -- se o módulo existe mas não está na lista
        return require('Módulo:Country data/' .. zone)
    end
end


local function flagIcon(data, flagtype, period, displayformat)
    local flagimage = getData(data, 'flag', flagtype, period)
    if flagimage then
        return printFlag(flagimage, '', displayformat)
    end
end

function p.standarddisplay(zone, args)
    if not zone then
        return nil
    end
    -- limpando as configurações
    if not args then
        args = {}
    end
    for i, j in pairs(args) do
        args[i] = mw.text.trim(j) -- remove whitespaces
        if args[i] == '' then args[i] = nil end
    end

   -- adicionar valores padrão
    local size = args.flagsize or '20x15'
    local flagtype = args.type

    local align = args.align or 'left'
    local link = args.link
    local period = args.date
    local competition = args.competition
    local edition = args.edition
    local extra = ''
   
    local success, data = pcall(getDatatable, zone)
    if not success then
        if args.strict then
            return error('local não reconhecido')
        end
        return nil
    end
   
    -- image
    local flag = flagIcon(data, flagtype, period)
    if (args.label == '-') then
        return flag, true
    end

    -- text
    local text
    local label = getLabel(data, flagtype)
    local link = getLink(data, flagtype)

    if competition then
        competition = _getCompetition(linguistic.toascii(competition),args["edição"])
    end
    if link and competition then
        link = link .. ' ' .. competition
    end

    if link then
        text = '[[' .. link .. '|' .. label .. ']]'
    end

    -- se os dados forem extraídos de um formulário padrão como módulo: Flag / domain, aplique regex
    if string.match(text, '%$') then
        text = applyregex(text, data)
    end
   
    local val
    if align == 'right' then
        val = text .. '&nbsp;' .. flag
    else
        val = flag .. '&nbsp;' .. text
    end
   
    return val, true -- true indica o sucesso
end

function p.nationality(zone, gender, number, topic, period)
    local success, data = pcall(getDatatable, zone)
    if not success then return
        zone
    end
   
    local str = getDemonym(data, gender, number)
    if not str then
        return zone
    end
    local link = getLink(data, topic, period)
    if link then
        str = '[[' .. link .. '|' .. str .. ']]'
    end
    return str, true-- true indica sucesso
end


function p.getNationality(args) -- obter a nacionalidade de uma pessoa no Wikidata na forma de adjetivos
    if not args then
        return nil
    end
    local wikidata = require "Módulo:Infobox/Wikidata"
    local complexdate = require "Módulo:Data complexa"
   
    if type(args) == 'string' then -- se apenas um argumento é a entidade a usar
        args {item = args}
    end
    if args.args then -- se vem do quadro
        args = args.args
    end
    local item = args.item or args[1]
   
    -- define a variável genéro para o elemento
    local vals = {
        ['Q6581072'] = 'f',
        ['Q6581097'] = 'm',
        default      = '?'
    }
    local gender = args.gender
    if not gender then
        gender = wikidata.formatStatements{entity = item, property = 'P21', displayformat = 'raw'}
        gender = vals[gender] or vals.default
    end
    -- desativação se data de nascimento antes da era contemporânea: muitas imprecisões e anacronismos
    local mindate = args.mindate or '1789'
    if mindate ~= "-" then
        local birthdate = wikidata.formatStatements{entity = item, property = 'P569', displayformat = 'raw', numval = 1}
        if (not birthdate) or complexdate.before(mindate, birthdate) then
            return nil
        end
    end
    return wikidata.formatStatements{
            property = 'P27',
            vals = statements,
            showdate = true,
            entity = item,
            conjtype = 'and',
            removedupes = true,
            linktopic = '-',
            displayformat =
                function(snak)
                    local g = gender -- tipo da pessoa, para exibição do genéro
                    if g == '?' then -- se desconhecido, no masculino
                        g = 'm'
                    end
                    local val, success = p.nationality(wikidata.getId(snak), g)
                    if not success then
                        val = wikidata.formatSnak(snak)
                    end
                    return val
                end
    }
end

return p