Module:ElectoralCalendarArticle

From Elections Wiki
Jump to navigation Jump to search

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

local p = {}

function p.generateArticle(frame)
    local dataPage = "Data:Election_Data.json"

    local dataTitle = mw.title.new(dataPage)
    if not dataTitle then
        return "could not find data page '" .. dataPage .. "'!"
    end

    local dataContent = dataTitle:getContent()
    if not dataContent then
        return "could not retrieve content from '" .. dataPage .. "'!"
    end

    local APIData = mw.text.jsonDecode(dataContent)
    if not APIData then
        return "invalid JSON in '" .. dataPage .. "'!"
    end

    local allElections = {}
    for region, elections in pairs(APIData) do
        for _, election in ipairs(elections) do
            table.insert(allElections, {
                region = string.gsub(region, "_", " "), 
                election_name = election.election_name,
                election_type = election.election_type,
                wiki_url = election.wiki_url,
                description = election.description,
                date = string.sub(election.date, 1, 10)
            })
        end
    end

    table.sort(allElections, function(a, b)
        return a.date < b.date
    end)

    local groupByDate = {}
    for _, election in ipairs(allElections) do
        if not groupByDate[election.date] then
            groupByDate[election.date] = {}
        end
        table.insert(groupByDate[election.date], election)
    end

    local sortedDates = {}
    
    for date in pairs(groupByDate) do
        table.insert(sortedDates, date)
    end
    
    table.sort(sortedDates)

    local function formatDate(isoDate)
        local year, month, day = isoDate:match("^(%d+)%-(%d+)%-(%d+)$")
        return os.date("%B ", os.time({year = year, month = month, day = day})) .. tonumber(day)
    end

    local output = {}
    for _, date in ipairs(sortedDates) do
        table.insert(output, "== " .. formatDate(date) .. " ==")

        local groupByType = {}
        for _, election in ipairs(groupByDate[date]) do
            if not groupByType[election.election_type] then
                groupByType[election.election_type] = {}
            end
            table.insert(groupByType[election.election_type], election)
        end

        for electionType, electionsByType in pairs(groupByType) do
            table.insert(output, "=== " .. electionType .. " ===")
            for _, election in ipairs(electionsByType) do
                table.insert(output, "*[[File:Flag of " .. election.region .. ".svg|16px]] [[Elections in " .. election.region .. "|" .. election.region .. "]]: " .. '[[' .. election.wiki_url .. '|' .. election.election_name .. ']]')
            end
        end
    end

    return table.concat(output, "\n")
end

return p