Module:GenerateID

From TANGOWIKI-TITAF
Revision as of 01:19, 16 April 2025 by Donxello (talk | contribs)

Documentation for this module may be created at Module:GenerateID/doc

-- Module:GenerateID
-- This module generates IDs for Persons, Groups, and GroupMemberships

local p = {}
local digits = 7

-- Reserved Ranges:
-- Person: 9958802 - 9988802
-- Group:  0031181 - 0099999
-- Membership: 0090001 - 0900000

function p.personID()
    return p._generateRandomID("TITAF-P-", "[[Category:TangoPeople]]", "TITAF%%-P%%-(%d+)", 9958802, 9988802)
end

function p.groupID()
    return p._generateRandomID("TITAF-G-", "[[Category:MusicalGroups]]", "TITAF%%-G%%-(%d+)", 31181, 9999999)
end

function p.membershipID()
    return p._generateRandomID("TITAF-R-", "[[Category:PersonGroupMemberships]]", "TITAF%%-R%%-(%d+)", 90001, 900000)
end

function p._generateRandomID(prefix, category, pattern, min, max)
    math.randomseed(os.time())
    local usedIds = {}
    local allPages = mw.smw.ask {
        category,
        "?=page",
        "limit=5000"
    }

    if allPages then
        for _, result in ipairs(allPages) do
            local title = result["page"] or ""
            local idNum = title:match(pattern)
            if idNum then
                usedIds[idNum] = true
            end
        end
    end

    local attempts = 0
    while attempts < 1000 do
        local randomNum = math.random(min or 1, max or 9999999)
        local formatted = string.format("%0" .. digits .. "d", randomNum)
        if not usedIds[formatted] then
            return prefix .. formatted
        end
        attempts = attempts + 1
    end

    return prefix .. "ERROR"
end

return p