Módulo:Cat principal

-- This module implements {{cat main}}.

local mHatnote = require('Módulo:Hatnote')
local mFormatLink = require('Módulo:Format link')
local yesno = require('Módulo:Yesno')
local mTableTools -- lazily initialise
local mArguments -- lazily initialise

local p = {}

function p.catMain(frame)
    mTableTools = require('Módulo:TableTools')
    mArguments = require('Módulo:Arguments')
    local args = mArguments.getArgs(frame, {wrappers = 'Predefinição:Cat principal'})
    local pages = mTableTools.compressSparseArray(args)
    local options = {
        article = args.article,
        selfref = args.selfref
    }
    return p._catMain(options, unpack(pages))
end

function p._catMain(options, ...)
    options = options or {}

    -- Get the links table.
	local links = mFormatLink.formatPages({}, {...})
	if not links[1] then
		local page = mw.title.getCurrentTitle().text
		links[1] = mFormatLink._formatLink{link = page}
	end
	for i, link in ipairs(links) do
		links[i] = string.format("'''%s'''", link)
	end

    -- Get the pagetype.
	local pages = {...}
	local pagetype 
	
	if options.article ~= nil then
		pagetype = yesno(options.article) ~= false and 'artigo' or 'página'
	elseif pages and pages[1] then
		local page = pages[1]:gsub("|.*","")
		pagetype = mw.title.new(page).namespace == 0 and "artigo" or "página"
	else
		pagetype = "artigo"
	end

    -- Work out whether we need to be singular or plural.
    local stringToFormat
    if #links > 1 then
        stringToFormat = 'Os [[Wikipédia:Artigo|%ss]] principais desta [[Wikipédia:Categoria|categoria]] são %s.'
    else
        stringToFormat = 'O [[Wikipédia:Artigo|%s]] principal desta [[Wikipédia:Categoria|categoria]] é %s.'
    end

    -- Get the text.
    local text = string.format(
        stringToFormat,
        pagetype,
        mw.text.listToText(links)
    )
    
    -- Pass it through to Module:Hatnote.
    local hnOptions = {}
    hnOptions.selfref = options.selfref
    hnOptions.extraclasses = 'relarticle mainarticle'

    return mHatnote._hatnote(text, hnOptions)
end

return p