Module:InterviewNavigation

From JoJo's Bizarre Encyclopedia - JoJo Wiki
Revision as of 23:39, 2 May 2023 by Vish (talk | contribs)
Jump to navigation Jump to search

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

local p = {}

local function parse_date(date_string)
    local month_name, day, year = date_string:match("(%a+)%s*(%d*),%s*(%d+)")
    local month_number = mw.language.getContentLanguage():formatDate("n", month_name .. " 1, " .. year)

    return {
        year = tonumber(year),
        month = tonumber(month_number),
        day = tonumber(day)
    }
end

local function compare_dates(a, b)
    a.day = a.day or 1
    b.day = b.day or 1

    if a.year ~= b.year then
        return a.year < b.year
    elseif a.month ~= b.month then
        return a.month < b.month
    else
        return a.day < b.day
    end
end

local function load_and_sort_interviews()
    local content = mw.loadJsonData("JoJo Wiki:Interviews")
    local interviews = content.interviews

    -- Sort interviews by date
    table.sort(interviews, function(a, b)
        local a_date = parse_date(a.date)
        local b_date = parse_date(b.date)
        return compare_dates(a_date, b_date)
    end)

    return interviews
end

local function find_prev_and_next_interviews(sorted_interviews, current_title)
    local prev, next
    local formatted_title = current_title:gsub("Interview:", "")

    for i, interview in ipairs(sorted_interviews) do
        if interview.title == formatted_title then
            prev = i > 1 and sorted_interviews[i - 1] or nil
            next = i < #sorted_interviews and sorted_interviews[i + 1] or nil
            break
        end
    end

    return prev, next
end

function p.main(frame)
    local current_title = frame.args[1]
    local nav_type = frame.args[2]

    local sorted_interviews = load_and_sort_interviews()
    local prev_interview, next_interview = find_prev_and_next_interviews(sorted_interviews, current_title)

    mw.log("Sorted Interviews:")
    mw.logObject(sorted_interviews)

    if nav_type == "prev" and prev_interview then
        return prev_interview.title
    elseif nav_type == "next" and next_interview then
        return next_interview.title
    else
        return ""
    end
end

return p