Módulo:Infobox/Ciclista/Testes

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



Descrição[editar código-fonte]

Este módulo tem funções auxiliares para criar infocaixas.

Uso[editar código-fonte]

Outra documentação:

local person = require "Módulo:Infobox/Funções/Pessoa"
local Wikidata = require "Módulo:Infobox/Wikidata"
local wikibase = mw.wikibase
local Complexedate = require "Módulo:Data complexa"
local wikidataON=true
local wikidataManagedON=true
local finalYear=2030
local initialYear=1900
local onlyRoad=true
local presentTeamLabel

-- lazy-filled by listofTeamTable(), on first call of amateurTeamTable() or proTeamTable()
local teamAmateur, teamPro, teamMountainBike, teamCycloCross, teamTrack, nationalTeam,managedTeam
local itemID

-- ##### Functions from Cycling race module copied #####
--[[ Iterator to get all statements for an entity and property which are not deprecated and have a value]]
local function nextStatement(state, i)
    local s
    repeat
        i = i + 1
        local s = state[i]
        if s and s.rank ~= 'deprecated' and s.mainsnak.snaktype == 'value' then
            return i, s
        end
    until s == nil
end
local function statements(QID, PID)
    return nextStatement, wikibase.getAllStatements(QID, PID), 0
end

--[[ Get any value for a property which is not deprecated ]]
local function firstValue(QID, PID, field)
    local ss = wikibase.getAllStatements(QID, PID)
    for _, s in pairs(ss) do
        if s.rank ~= 'deprecated' and s.mainsnak.snaktype == 'value' then
            return field and s.mainsnak.datavalue.value[field] or s.mainsnak.datavalue.value
        end
    end
end

--[[ Go from season of a team to the team ]]
local function getParentID(teamID)
    return firstValue(teamID, 'P361', 'id') -- P361 is 'part of'
        or firstValue(teamID, 'P5138', 'id') -- P5138 is 'season of club or team'
end

--[[ Get sitelink with no wiki no formating ]]
local function getRawTeamLink(teamID)
    local sitelink
    local parentID = getParentID(teamID)
    if parentID then -- try parent team first
        sitelink = mw.wikibase.getSitelink(parentID)
    end
    if not sitelink then
        sitelink = mw.wikibase.getSitelink(teamID)
    end
    return sitelink
end

--[[ Get a Wikidata statement for an entity and property valid at the given timevalue ]]
local function checkTime(s, time)
    local start, startPrecision, END, endPrecision
    local q = s.qualifiers
    if q then
        if q.P580 and q.P580[1] and    q.P580[1].snaktype == 'value' then -- P580 is start time
            start = q.P580[1].datavalue.value.time
            startPrecision = q.P580[1].datavalue.value.precision
            if startPrecision == 9 then -- precision is years
                start = string.sub(start, 1, 5) -- Cut of everything after year
            elseif startPrecision == 10 then -- precision is months
                start = string.sub(start, 1, 8) -- Cut of everything after month
            end
        end
        if q.P582 and q.P582[1] and q.P582[1].snaktype == 'value' then -- P582 is end time
            END = q.P582[1].datavalue.value.time
            endPrecision = q.P582[1].datavalue.value.precision
        end
    end
    if not start or start <= time then
        if not END then
            return s
        end
        if endPrecision == 9 then -- precision 9 is 'years'
            END = string.sub(END, 1, 6) .. '13' -- Set month to 13
        elseif endPrecision == 10 then -- precision 10 is 'months'
            END = string.sub(END, 1, 9) .. '32' -- Set day to 32
        end
        if END >= time then
            return s
        end
    end
    return nil
end

local function getStatementForTime(ID, property, time)
    local temp
    for _, s in statements(ID, property) do
        temp =checkTime(s, time)
        if temp then return temp end
    end
    return nil
end

local function getOfficialName(teamID, timeOfRace) -- for team
    local p1448 = getStatementForTime(teamID, 'P1448', timeOfRace) -- P1448 is official name
    if p1448 then
        if available_lang_priority and p1448.qualifiers and p1448.qualifiers.P1448 then
            local q = p1448.qualifiers.P1448
            local wantedLanguages = {}
            local best = 999
            local name
            for i, lang in ipairs(translations.lang_priority) do
                wantedLanguages[lang] = i
            end
            for _, l in pairs(q) do
                if l.snaktype == 'value' then
                    local lang = l.datavalue.value.language
                    if wantedLanguages[lang] and wantedLanguages[lang] < best then
                        best = wantedLanguages[lang]
                        name = l.datavalue.value.text
                    end
                end
            end
            if name then return name, true end
        end
        return p1448.mainsnak.datavalue.value.text, false
    end
    local label=wikibase.getLabel(teamID)
    return label -- No official name, try label
end

local function getCountryName(countryID)
    local name = ''
    local available, translations = pcall(require, "Module:Cycling race/lang")
    local available_list = available and type(translations.list) == "function"
   
    if available_list then
        name = translations.list(countryID)
    end
    if name == '' then
        local label, lang = wikibase.getLabelWithLang(countryID)
        --[[ Uses standard language fallback. Should not return nil, nil, as all countries have English labels. ]]
        if lang == wikilang then
            name = label
        elseif lang then
            name = label .. ' (' .. lang .. ')'
        end
    end
    return name
end

--[[ Get sitelink, categoryID and maybe country for a team.
    Returns sitelink, team category ID, countryID (only countryID if country arg is true ]]
local function getTeamLinkCat(teamID, timeOfRace, country)
    --countryID is not used in this module
    local name, sitelink, parentID, catID
    -- Find team category
    local teamCats = {
        Q6154783 = true, Q20638319 = true, Q382927 = true, Q1756006 = true, Q23726798 = true,
        Q20738667 = true, Q28492441 = true, Q20639848 = true, Q20639847 = true, Q20652655 = true,
        Q20653563 = true, Q20653564 = true, Q20653566 = true, Q2466826 = true, Q26849121 = true,
        Q78464255 = true, Q80425135=true
    }
    for _, p31 in statements(teamID, 'P31') do
        if checkTime(p31, timeOfRace) then
            local natureID = p31.mainsnak.datavalue.value.id
            if teamCats[natureID] then
                catID = natureID
                break
            end
        end
    end
    --main team
    -- Find country if needed
    local countryID
    if country or catID == 'Q23726798' or catID == 'Q20738667' then
        countryID = firstValue(teamID, 'P1532', 'id') -- P17 is country for sport
        if countryID == nil then
            countryID = firstValue(teamID, 'P17', 'id') -- P17 is country
        end
    end
    if countryID and (catID == 'Q23726798' or catID == 'Q20738667') then
        -- It is a national cycling team
        name = getCountryName(countryID)
        if catID == 'Q20738667' then -- national cycling team U23
            local s
            if wiki == 'fr' then s = ' espoirs'    end
            name = name .. s
        end
        sitelink = getRawTeamLink(teamID)
    else
        -- It is not a national cycling team
        local isLocal
        parentID = getParentID(teamID)
        if parentID then -- try parent team first
            sitelink = wikibase.getSitelink(parentID)
            name, isLocal = getOfficialName(parentID, timeOfRace)
        end
        if not sitelink then
            sitelink = wikibase.getSitelink(teamID)
        end

        if not name or (not isLocal and available_lang_priority) then
            local partName, partIsLocal = getOfficialName(teamID, timeOfRace)
            if partName and (not name or partIsLocal) then
                name = partName
            end
        end
    end
    if sitelink then
        if name then
            sitelink = '[[' .. sitelink .. '|' .. name .. ']]'
        else
            sitelink = '[[' .. sitelink .. ']]'
        end
    else
        if name then
            sitelink = name
        else
            sitelink = (parentID and wikibase.getLabel(parentID)) or
                wikibase.getLabel(teamID) or 'No name'
        end
    end
    return sitelink, catID
end

-- ##### Functions for the Infobox #####
--For the case with direct input of the parameters
local function teamValue( teamParam, dateParam )
    return function( localdata )
        local names, periods = localdata[ teamParam ], localdata[ dateParam ]
        if not names then
            return nil
        end
        if names then
            names =  mw.text.split(names, '<br />')
            periods = mw.text.split(periods or '', '<br />')
        end
        local tab =  mw.html.create('table')
        for i, name in pairs(names) do
            local row = mw.html.create('tr')
                :tag('td'):wikitext(periods[i] or ''):done()
                :tag('td'):wikitext(name):done()
            tab:node(row):done()
        end
        tab:done()
        return tostring(tab)
    end
end

local function checkDis(q)
    dis="road"
    if q and q.P642 and q.P642[1] and q.P642[1].snaktype == 'value' then
        if q.P642[1].datavalue.value.id == 'Q520611' or q.P642[1].datavalue.value.id =='Q1031445' then
            onlyRoad=false
            dis="mountainBike"
        elseif  q.P642[1].datavalue.value.id == 'Q335638' then
            onlyRoad=false
            dis="cycloCross"
        elseif q.P642[1].datavalue.value.id == 'Q221635' then
            onlyRoad=false
            dis="track"           
        end
    end
    return dis
end

local function presentTeam(item)
    local tToday=os.date("*t") 
    local teamId, result, teamLink, teamLinkRoad, row
    local plural=false
    if mw.ustring.len(tToday["month"])==1 then tToday["month"]='0'..tToday["month"] end
    if mw.ustring.len(tToday["day"])==1 then tToday["day"]='0'..tToday["day"] end   
    local today='+'..tToday["year"].."-"..tToday["month"].."-"..tToday["day"].."T00:00:00Z"
    finalYear=tonumber(tToday["year"])+1 --global
       
    itemID=item:getId()
    local temp=firstValue(itemID, 'P569','time')
    if temp then
        _, _, initialYear,_,_ = string.find(temp, "(%d+)-(%d+)-(%d+)")
    end

    for _, s in statements(itemID, 'P54') do
        p54 =checkTime(s, today) --present Team
        if p54 then
            teamId= p54.mainsnak.datavalue.value.id
            teamLink=getTeamLinkCat(teamId, today)
            dis=checkDis(p54.qualifiers)
            row=nil
            if dis=='road' then
                teamLinkRoad=teamLink
            elseif dis=='mountainBike' then
                row=teamLink..' (BTT)'
            elseif dis=='cycloCross' then
                row=teamLink..' (ciclo-cross)'
            else
                row=teamLink..' (pista)'
            end
           
            if row then
                if not result then
                    result = row
                else
                    result= result..'<br/>'..row
                    plural = true
                end
            end
        end
    end
    if teamLinkRoad and result then --put road first
        result = teamLinkRoad..' (rota)<br/>'..result
        plural= true
    elseif teamLinkRoad then
        result = teamLinkRoad
    end
   
    if plural then
        presentTeamLabel="Equipas atuais"
    else
        presentTeamLabel="Equipa atual"
    end
    return result
end

local function convertDate(date1, beginOrEnd)
    if date1==0 then
        if beginOrEnd==0 then --begin
            y1=tostring(initialYear)
            m1="01"
            d1="01"
        else
            y1=tostring(finalYear)
            m1="12"
            d1="31"
        end
    else
        _, _, y1,m1,d1 = string.find(date1, "(%d+)-(%d+)-(%d+)")
        if m1 ==nil or m1=="00" then
            if beginOrEnd==0 then --begin
                m1="01"
                d1="01"
            else--end
                m1="12"
                d1="31"
            end
        end
    end
    return '+'..y1.."-"..m1.."-"..d1.."T00:00:00Z"
end

local function getStartendTime(q)
    -- look for start and end time of team by the riders
    local startTime, endTime, stagiaire, dis

    if q then
        if q.P580 and q.P580[1] and    q.P580[1].snaktype == 'value' then -- P580 is start time
            startTime =q.P580[1].datavalue.value.time
        elseif q.P585 and q.P585[1] and    q.P585[1].snaktype == 'value' then
            startTime =q.P585[1].datavalue.value.time
        else
            startTime =0
        end
        startTime=convertDate(startTime, 0)
       
        if q.P582 and q.P582[1] and q.P582[1].snaktype == 'value' then
            endTime =q.P582[1].datavalue.value.time
        elseif q.P585 and q.P585[1] and    q.P585[1].snaktype == 'value' then
            endTime =q.P585[1].datavalue.value.time
        else
            endTime=0
        end
        endTime=convertDate(endTime, 1)
       
        if q.P39 and q.P39[1] and    q.P39[1].snaktype == 'value' then
            stagiaire = q.P39[1].datavalue.value
        else
            stagiaire = nil
        end
        dis=checkDis(q)
    end
    return startTime, endTime, stagiaire, dis
end

local function listofTeam(item, PID)
    --first we have to read P54 of the rider
    local riderteam={}
    if not itemID then itemID=item:getId() end
   
    for ii, p54 in statements(itemID, PID) do --itemID loaded in presentTeam
        if p54 then
            teamId=p54.mainsnak.datavalue.value.id
        else
            teamId=nil
        end
        local q = p54.qualifiers
        if q then
            local startTime, endTime, stagiaire, dis=getStartendTime(q)
            table.insert(riderteam,{teamId=teamId, startTime=startTime, endTime=endTime, stagiaire=stagiaire, dis=dis})
        end
    end
    return riderteam
end

local function formatDate(thisDate)
    if thisDate=='' then
        return ''
    else
        local month=math.ceil(thisDate['month']/2)
        if month==12 or month==1 then
            return thisDate['year']
        else
            local date1='+'..thisDate['year'].."-"..month.."-".."01".."T00:00:00Z"
            local newobj = Complexedate.splitDate(date1) 
            if newobj.month == 0 or newobj.month==nil then
                return newobj.year
            else
                return newobj.month..'.'..newobj.year
            end
        end
    end
end

local function getTeamInfo(teamId,mm,yy,dd,managedTeam)
    --get the nature and name of the team for the date mm,yy
    mm=tostring(mm)
    yy=tostring(yy)
    dd=tostring(dd)
    if mw.ustring.len(mm)==1 then mm='0'..mm end
   
    thistime='+'..yy.."-"..mm.."-"..dd.."T00:00:00Z"
    local sitelink, teamNature=getTeamLinkCat(teamId, thistime, false)
    local cat, boolean
    local amateurcat={Q20639848=true,Q20652655=true,Q26849121=true}
    local nationalcat={Q23726798=true, Q20738667=true, Q54660600=true, Q54555994=true, Q99658502=true}
   
    if managedTeam then
       cat=nationalcat
    else
       cat=amateurcat
    end

    if cat[teamNature] then --club
        boolean=true--amateur / national selection
    else
        boolean=false--pro  / not national selection
    end
    return boolean, sitelink
end

--for managed team, the table should be splat, as we can be national trainer and team trainer at the same time
local function analyzeManagedTeam(teamRider)
    local natTeamOut, managedTeamOut={},{}
    local dis="road"
    local managedTeam=true
   
    for i=1,24 do --init table
        natTeamOut[i]={}
        managedTeamOut[i]={}
        for j=initialYear,finalYear do
            natTeamOut[i][j]={ amateurTeam, link, stagiaire=nil}
            managedTeamOut[i][j]={amateurTeam,link, stagiaire=nil}
        end
    end

    local teamId, natTeam, sitelink
    local sYear, sMonth,eYear, eMonth, sDay, eDay

    if teamRider==nil then return nil end
   
    for _, v in pairs(teamRider) do --for each team where was the rider
        if v['dis']==dis then
            --exception managed at the reading
            _, _, sYear,sMonth,sDay = string.find(v['startTime'], "(%d+)-(%d+)-(%d+)")
            _, _, eYear,eMonth,eDay = string.find(v['endTime'], "(%d+)-(%d+)-(%d+)")
   
            sYear=tonumber(sYear)
            sMonth=tonumber(sMonth)
            eYear=tonumber(eYear)
            eMonth=tonumber(eMonth)
   
            if sYear<=eYear then --test of congruence
                for yy=sYear,eYear do
                    for mm=1,12 do
                        local mmindex=(mm-1)*2+1
                        --avoid reading info where the team is not the one of the rider
                        getinfo=true
                        if (yy==sYear and mm<sMonth) or (yy==eYear and mm>eMonth) then
                            getinfo=false
                        end
   
                        if getinfo then
                            if (yy==sYear) and (mm==sMonth) and (sDay~='01' and sDay~='00' and sDay~=nil)then
                                natTeam, sitelink=getTeamInfo(v['teamId'],mm,yy,sDay, managedTeam)
                                if natTeam then
                                    natTeamOut[mmindex+1][yy]['amateurTeam']=true
                                    natTeamOut[mmindex+1][yy]['link']=sitelink
                                else
                                    managedTeamOut[mmindex+1][yy]['amateurTeam']=false
                                    managedTeamOut[mmindex+1][yy]['link']=sitelink
                                end   
                            else
                                natTeam, sitelink=getTeamInfo(v['teamId'],mm,yy,1, managedTeam)
                                if natTeam then
                                    natTeamOut[mmindex][yy]['amateurTeam']=true
                                    natTeamOut[mmindex][yy]['link']=sitelink
                                    if natTeamOut[mmindex+1][yy]['amateurTeam']==nil or v['stagiaire'] then --to avoid problem with team name change during the month
                                        natTeam, sitelink=getTeamInfo(v['teamId'],mm,yy,30,managedTeam)
                                        natTeamOut[mmindex+1][yy]['amateurTeam']=true --a nat team stays a nat team
                                        natTeamOut[mmindex+1][yy]['link']=sitelink
                                    end
                                else
                                    managedTeamOut[mmindex][yy]['amateurTeam']=false
                                    managedTeamOut[mmindex][yy]['link']=sitelink
                                    if managedTeamOut[mmindex+1][yy]['amateurTeam']==nil or v['stagiaire'] then --to avoid problem with team name change during the month
                                        natTeam, sitelink=getTeamInfo(v['teamId'],mm,yy,30,managedTeam)
                                        managedTeamOut[mmindex+1][yy]['amateurTeam']=false --a nat team stays a nat team
                                        managedTeamOut[mmindex+1][yy]['link']=sitelink
                                    end
                                end
                            end
                        end
                    end
                end
            end
        end
    end
    return natTeamOut, managedTeamOut --a filled matrix with the link and nature of the teams
end


local function analyzeTeam(teamRider, dis)
    local teamOut={} --as there can be a supposition
    for i=1,24 do --init table
        teamOut[i]={}
        for j=initialYear,finalYear do
            teamOut[i][j]={ amateurTeam, link, stagiaire, dis}
        end
    end
   
    local managedTeam=false
    local teamId, amateurTeam, sitelink
    local sYear, sMonth,eYear, eMonth, sDay, eDay

    if teamRider==nil then return nil end
   
    for _, v in pairs(teamRider) do --for each team where was the rider
        if v['dis']==dis then
            --exception managed at the reading
            _, _, sYear,sMonth,sDay = string.find(v['startTime'], "(%d+)-(%d+)-(%d+)")
            _, _, eYear,eMonth,eDay = string.find(v['endTime'], "(%d+)-(%d+)-(%d+)")
   
            sYear=tonumber(sYear)
            sMonth=tonumber(sMonth)
            eYear=tonumber(eYear)
            eMonth=tonumber(eMonth)
   
            if sYear<=eYear then --test of congruence
                for yy=sYear,eYear do
                    for mm=1,12 do
                        local mmindex=(mm-1)*2+1
                        --avoid reading info where the team is not the one of the rider
                        getinfo=true
                        if (yy==sYear and mm<sMonth) or (yy==eYear and mm>eMonth) then
                            getinfo=false
                        end
   
                        if getinfo then
                            if (yy==sYear) and (mm==sMonth) and (sDay~='01' and sDay~='00' and sDay~=nil)then
                                amateurTeam, sitelink=getTeamInfo(v['teamId'],mm,yy,sDay, managedTeam)
                                teamOut[mmindex+1][yy]['amateurTeam']=amateurTeam
                                teamOut[mmindex+1][yy]['link']=sitelink
                                teamOut[mmindex+1][yy]['stagiaire']=v['stagiaire']
                                teamOut[mmindex+1][yy]['dis']=v['dis']
                            else
                                amateurTeam, sitelink=getTeamInfo(v['teamId'],mm,yy,1, managedTeam)
                                teamOut[mmindex][yy]['amateurTeam']=amateurTeam
                                teamOut[mmindex][yy]['link']=sitelink
                                teamOut[mmindex][yy]['stagiaire']=v['stagiaire']
                                teamOut[mmindex][yy]['dis']=v['dis']
                                if teamOut[mmindex+1][yy]['amateurTeam']==nil or v['stagiaire'] then --to avoid problem with team name change during the month
                                    amateurTeam, sitelink=getTeamInfo(v['teamId'],mm,yy,30, managedTeam)
                                    teamOut[mmindex+1][yy]['amateurTeam']=amateurTeam
                                    teamOut[mmindex+1][yy]['link']=sitelink
                                    teamOut[mmindex+1][yy]['stagiaire']=v['stagiaire']
                                    teamOut[mmindex+1][yy]['dis']=v['dis']
                                end
                            end
                        end
                    end
                end
            end
        end
    end
    return teamOut --a filled matrix with the link and nature of the teams
end

--local function insertTeam(teamAmateur,teamPro,teamMountainBike, teamCycloCross, teamTrack, sDate,eDate,v)
local function insertTeam(teamAmateur,teamPro, sDate,eDate,v)
    local sDate2=formatDate(sDate)
    local eDate2=formatDate(eDate)
    local ins = {link=v['link'], sDate=sDate2,eDate=eDate2,stagiaire=v['stagiaire']}

    if v['amateurTeam']  then
        table.insert(teamAmateur,ins)
    else
        table.insert(teamPro,ins)
    end
    return teamAmateur,teamPro
end

local function synthetizeTable(analyzedTeam)
    local teamPro, teamAmateur, tempTeam, tempsDate, tempeDate={}, {},{},{},{}
    local empty=true
    local active=false

    for yy=initialYear,finalYear do
        for mm=1,24 do
            local v=analyzedTeam[mm][yy]
            if v['amateurTeam']~=nil then
                if empty then --first line
                    active=true
                    empty=false
                    tempTeam=v
                    tempsDate['month']=mm
                    tempsDate['year']=yy
                else
                    if tempTeam['amateurTeam']==v['amateurTeam'] and tempTeam['link']==v['link']
                    and tempTeam['stagiaire']==v['stagiaire'] then --no change, the case of same team but different disciplines is not considered
                        if yy==finalYear and mm==24 then--present team
                        teamAmateur,teamPro=insertTeam(teamAmateur,teamPro,tempsDate,'',tempTeam)
                        end
                    else--change
                        --save the old
                        if active then --if active false then it was already saved
                            if mm==1 then
                                tempeDate['year']=yy-1
                                tempeDate['month']=24
                            else
                                tempeDate['year']=yy
                                tempeDate['month']=mm-1
                            end
                            teamAmateur,teamPro=insertTeam(teamAmateur,teamPro,tempsDate,tempeDate,tempTeam)
                        end
                        --save the new
                        active=true
                        tempTeam=v
                        tempsDate['month']=mm
                        tempsDate['year']=yy
                    end --change
                end--first line
            elseif active then --there was a team and now there is an empty period
                active=false
                --save the old
                if mm==1 then
                    tempeDate['year']=yy-1
                    tempeDate['month']=24
                else
                    tempeDate['year']=yy
                    tempeDate['month']=mm-1
                end

                teamAmateur,teamPro=insertTeam(teamAmateur,teamPro,tempsDate,tempeDate,tempTeam)
                tempTeam['link']=nil --avoid problem if the rider comes back in the same team
            end 
        end-- for mm
    end--for yy
    return teamAmateur,teamPro
end

local function listOfManagedTeamTable(itemID)
    local managedTeamRider = listofTeam(itemID, 'P6087')--raw list of team
    if not managedTeamRider then
        return nil, nil
    end
   
    local natTeamOut, managedTeamOut=analyzeManagedTeam(managedTeamRider) --table with links and nature of teams
    --global
    nationalTeam,_=synthetizeTable(natTeamOut)
    _,managedTeam=synthetizeTable(managedTeamOut)
end

local function listofTeamTable(item)
    local teamRider = listofTeam(item, 'P54')--raw list of team
    if not teamRider then
        return nil
    end
    local analyzedTeam1=analyzeTeam(teamRider, "road") --table with links and nature of teams
    teamAmateur,teamPro=synthetizeTable(analyzedTeam1) --table formated, global
    local analyzedTeam2=analyzeTeam(teamRider, "mountainBike")
    _, teamMountainBike=synthetizeTable(analyzedTeam2)
    local analyzedTeam3=analyzeTeam(teamRider, "cycloCross")
    _, teamCycloCross=synthetizeTable(analyzedTeam3)
    local analyzedTeam4=analyzeTeam(teamRider, "track")
    _, teamTrack=synthetizeTable(analyzedTeam4)   
end   

local function TeamTable(teamRider, titlesing, titleplural)
    local temprows=nil
    local title = titleplural
    if teamRider and #teamRider~=0 then
        local nametemp, periodtemp
        local rows =  mw.html.create('table')
        for _, v in pairs(teamRider) do
            nametemp=v['link']
            if v['sDate']==v['eDate'] then
                periodtemp=v['sDate']
            else
                periodtemp=v['sDate']..'-'..v['eDate']
            end
            if v['stagiaire'] then
                nametemp=nametemp..' (stagiaire)'
            end
            local row = rows:tag('tr')
            row:tag('td'):wikitext(periodtemp or '')
            row:tag('td'):wikitext(nametemp)
        end
        temprows=tostring(rows)
        if #teamRider == 1 then
            title = titlesing
        end
    else
        temprows=nil
    end
    return {type = 'table', title = title, rows = {{type = 'row', value = function () return temprows end}}}
end

local function managedTeamTable(localdata)
    local teamManagednames= localdata['equipas dirigidas']
    local teamManagedperiods=localdata['anos direção']
   
    if teamManagednames then
       wikidataManagedON=false
    end
   
    if wikidataManagedON then
        if managedTeam==nil and localdata.item then
            listOfManagedTeamTable(localdata.item)
        end   
        return TeamTable(managedTeam, 'equipa dirigida','equipas dirigidas')
    else
        return {type = 'table', title = 'equipas dirigées', rows = {{type = 'row', value = teamValue( 'equipas dirigidas', 'anos direção' )}}}
    end   
end

local function nationalTeamTable(localdata)
    if wikidataManagedON then --only with wikidata
        if nationalTeam==nil and localdata.item then
            listOfManagedTeamTable(localdata.item)
        end   
        return TeamTable(nationalTeam, 'Selecção nacional dirigida','Selecções nacionais dirigidas')
    else
        return {type = 'table', title = nil, rows = {{type = 'row', value = nil}}}
    end
end

local function amateurTeamTable(localdata)
    -- teamAmateur called before
    local NotUCInames = localdata['equipas não-UCI']
    local AmateurNames = localdata['equipas amadoras']
    local suffix =''

    if NotUCInames or AmateurNames or localdata['equipas UCI'] or localdata['equipas pro'] then
       wikidataON=false
    end

    if wikidataON then
        if teamAmateur==nil and localdata.item then
            listofTeamTable(localdata.item)
        end
        if not onlyRoad then
            suffix=' no ciclismo de estrada'
        end

        return TeamTable(teamAmateur, 'Equipa não-UCI'..suffix,'Equipas não-UCI'..suffix)
    else
        if NotUCInames then
            return {type = 'table', title = 'Equipas não-UCI', rows = {{type = 'row', value = teamValue( 'equipas não-UCI', 'anos não-UCI' )}}}
        else
            return {type = 'table', title = 'Equipas amadoras', rows = {{type = 'row', value = teamValue( 'equipas amadoras', 'anos amador' )}}}
        end
    end
end       

local function proTeamTable(localdata)
    local UCInames = localdata['equipas UCI']
    local ProNames = localdata['equipas pro']
    local suffix =''
   
    if wikidataON then
        if teamPro==nil and localdata.item then
            listofTeamTable(localdata.item)
        end
        if not onlyRoad then
            suffix=' no ciclismo em pista'
        end
   
        return TeamTable(teamPro, 'equipa UCI'..suffix,'equipas UCI'..suffix)
    else
        if UCInames then
            return {type = 'table', title = 'equipas UCI', rows = {{type = 'row', value = teamValue( 'equipas UCI', 'anos UCI' )}}}
        else
            return {type = 'table', title = 'equipas profissionais', rows = {{type = 'row', value = teamValue( 'equipas pro', 'anos pro' )}}}
        end
    end
end

local function mountainBikeTeamTable(localdata)
    --amateur or pro Team Table were already called
    if wikidataON and teamMountainBike~=nil then
        return TeamTable(teamMountainBike, 'equipa BTT','equipas BTT')
    else
        return {type = 'table', title = nil, rows = {{type = 'row', value = nil}}}
    end
end


local function cycloCrossTeamTable(localdata)
    --amateur or pro Team Table were already called
    if wikidataON and teamCycloCross~=nil then
        return TeamTable(teamCycloCross, 'equipa ciclo-cross','equipas ciclo-cross')
    else
        return {type = 'table', title = nil, rows = {{type = 'row', value = nil}}}
    end
end

local function trackTeamTable(localdata)
    --amateur or pro Team Table were already called
    if wikidataON and teamTrack~=nil then
        return TeamTable(teamTrack, 'equipa pista','equipas pista')
    else
        return {type = 'table', title = nil, rows = {{type = 'row', value = nil}}}
    end
end

local function listMedals()
  
     -- ajuste de parâmetros de dados
        local value = function(localdata)
                local value = localdata['medals'] or localdata['medalstemplate']
            if not value then
                           return nil
        end
    -- definições do estilo
    local class = "overflow nav " .. (localdata['class'] or '')
        local style = mw.getCurrentFrame():extensionTag('templatestyles', '', {src = 'Infobox/common.css'}) or {}

       local navbox
    navbox = mw.html.create('div')
           
        navbox
                :addClass(class)
                :css(style)
                :tag('div')
                :addClass('bordered')
                :wikitext(value)
                :done()
                :allDone()
        return navbox
     end
end

local function listItems( itemParam )
     local value = function(localdata)
         local str = localdata['itemParam']
         if not str then
             return nil
         end
         if str then
             str = mw.text.split(str, '<br />')
         end
         local tab =  mw.html.create('table')
         for i, str in pairs(str) do
             local row = mw.html.create('tr')
                 :tag('td'):wikitext(str):done()
          tab:node(row):done()
         end
         tab:done()
         return tostring(tab)
    end
end

return
    {
        maincolor = '#FFDF80',
        parts = {
            person.title('desporto'),
            person.mainimage('!Artigos de esporte sem imagens'),
            {type = 'table', title = 'Informações', rows = {
                person.othernames(),
                person.birth(),
                person.death(),
                person.placeofburial(),
                person.nationality(),
                {type = 'row', label = function ( item )
                    return presentTeamLabel or 'equipa actual' --plural or not, or not called
                    end
                , value = {'equipa', 'equipe'},
                wikidata = function ( item )
                    return presentTeam(item)
                    end,
                },
                {
                    type = 'row',
                    label = 'Especialidade',
                    singularlabel = 'Especialidade',
                    plurallabel = 'Especialidades',
                    value = {'funcao', 'papel'},
                    property = 'P413'
                },
                {type = 'row', label = 'Lateralização', property = 'P552'},
                --person.appearance(),
                {type = 'row', label = 'Grupo sanguíneo', property = 'P1853'},
                --person.family(),
                person.awards(),
                },
            },
            amateurTeamTable,
            proTeamTable,
            mountainBikeTeamTable,
            cycloCrossTeamTable,
            trackTeamTable,
            managedTeamTable,
            nationalTeamTable,
            {type = 'table', title = 'Principais vitórias', rows = {
            {type = 'row', value = {'maiores_vit', 'vitórias principais'}}}},
            {type = 'table', title = 'Recorde Medalhas1', rows = {{type = 'row', value = listItems( {'medaltemplates', 'medals'} )}}},
            {type = 'table', title = 'Recorde Medalhas2', rows = {{type = 'row', value = {'medaltemplates', 'medals'}}}},
                        listMedals(),
              person.website(),
            person.causamorte(),
                        person.assinatura(),
            person.placa(),
                person.sepultura(),
        }
    }