Documentation for this module may be created at Module:Sandbox/Retro/GA/doc

local p = {}

local function _findFreePageNum(titleBody)
    local pageNum = 1
    while true do
        local pageTitle = mw.title.new(titleBody .. pageNum)
        if not pageTitle.exists then
            return pageNum
        end
        pageNum = pageNum + 1
    end
end

-- Based on _findFreePageNum
function p.countPages(frame)
    local titleBody = frame.args[1] or ""
    local pageNum = 1
    while true do
        local pageTitle = mw.title.new(titleBody .. pageNum)
        if not pageTitle.exists then
            return pageNum - 1
        end
        pageNum = pageNum + 1
    end
end

local function titleParts(title, numSegments, firstSegment)
    -- Intended to replicate the behavior of {{#titleparts: ... }}
    -- Can probably be more efficient with pure Lua.
    return mw.getCurrentFrame:callParserFunction{'titleparts', {
        title, numSegments, firstSegment
    }}
end

-- Probably will want to use more descriptive variable names 
function p.GAR(frame)
    local currentTitle = mw.title.getCurrentTitle()
    if mw.isSubsting() and currentTitle.inNamespace(1) then
        local pageNum = _findFreePageNum("Talk:" .. currentTitle.text .. "/GA")
        local GARpageNum = _findFreePageNum("Wikipedia:Good article reassessment/" .. currentTitle.text .. "/")
        return "{{GAR/link|" .. frame:preprocess("~~~~~") .. "|page=" .. pageNum .. "|GARpage=" .. GARpageNum .. "|status= }}"
    else
        return frame:expandTemplate{
            title = "error",
            args = {
                frame:preprocess("This template should be '''substituted''' at the top of the article '''talk''' page.")
            }
        }
    end
end

-- Maybe specify the name further; this is currently only for community reviews
-- Should there be a variant for individual reviews?
function p.mostRecentReview(frame)
    currentTitle = mw.title.getCurrentTitle()
    -- ns comparison is inaccurate
    if mw.isSubsting()
    and currentTitle.inNamespace(4) -- Wikipedia namespace (see [[WP:NS]])
    and currentTitle.rootText == "Good article reassessment" then
        articleTitle = titleParts(currentTitle.text, 1, 2)
        local pageNum = _findFreePageNum("Talk:" .. articleTitle .. "/GA")
        if pageNum == 1 then
            return "GAN review not found"
        else
            return "[[" .. articleTitle .. "/GA" .. (pageNum - 1) .. "|Most recent review]]"
        end
    -- Error message:
    -- "    This template should be [[Wikipedia:Substitution|substituted]] on a community good article reassessment page."
    end
end

return p