Module:InterviewNavigation

From JoJo's Bizarre Encyclopedia - JoJo Wiki
Revision as of 22:49, 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)
    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 and b.day and a.day < b.day or false
    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

    for i, interview in ipairs(sorted_interviews) do
        if interview.title == current_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)

    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