Module:Calendar

From Angelina Jordan Wiki
Revision as of 22:07, 3 October 2025 by Most2dot0 (talk | contribs) (bugfix)

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

local p = {}
local json = mw.text.jsonEncode

-- Utility: split string
local function split(str, sep)
    local t = {}
    for token in string.gmatch(str or "", "[^"..sep.."]+") do
        table.insert(t, token)
    end
    return t
end

-- Query a Cargo table
local function queryCargo(tableName, fields, whereClause)
    if not mw.ext.cargo then
        error("Cargo extension not loaded (mw.ext.cargo is nil)")
    end
    local results = {}
    local q = mw.ext.cargo.query{
        tables = tableName,
        fields = fields,
        where = whereClause or ""
    }
    for row in q:iterator() do
        table.insert(results, row)
    end
    return results
end

-- Nest children under parent using key mapping
local function nestChildren(parentList, childList, parentKey, childKey, childLabel)
    for _, parent in ipairs(parentList) do
        parent[childLabel] = {}
        for _, child in ipairs(childList) do
            if parent[parentKey] == child[childKey] then
                table.insert(parent[childLabel], child)
            end
        end
    end
end

-- Main function
function p.getJSON(frame)
    local args = frame.args

    -- Tables (comma-separated)
    local tables = split(args.tables or "", ",")

    -- Multi-table parameters (semicolon-separated)
    local fieldsList = split(args.fields or "", ";")
    local whereList = split(args.where or "", ";")
    local nestDefs = split(args.nest or "", ";")

    -- Query each table
    local tableData = {}
    for i, tbl in ipairs(tables) do
        local fields = fieldsList[i] and split(fieldsList[i], ",") or {"*"}
        local whereClause = whereList[i] or ""
        tableData[tbl] = queryCargo(tbl, fields, whereClause)
    end

    -- Apply nestings
    for _, nestDef in ipairs(nestDefs) do
        -- Format: "childTable:parentKey=childKey:label"
        local childTable, keyMapping, childLabel = nestDef:match("([^:]+):([^=]+)=([^:]+):?(.*)")
        if childLabel == "" or not childLabel then
            childLabel = childTable
        end
        if tableData[childTable] then
            local parentKey, childKey = keyMapping:match("([^=]+)=?([^=]*)")
            if not childKey or childKey == "" then
                childKey = parentKey
            end
            nestChildren(tableData[tables[1]], tableData[childTable], parentKey, childKey, childLabel)
        end
    end

    return json(tableData[tables[1]] or {})
end

return p