Module:Chapters

From Candypedia
Revision as of 08:19, 19 May 2024 by SuitCase (talk | contribs)

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

-- Module:Chapters
local p = {}

function p.getChaptersList()
    local listPage = mw.title.new('Template:ChaptersList')
    if not listPage then
        return {}
    end

    local content = listPage:getContent()
    if not content then
        return {}
    end

    local chapters = {}
    for number, title, date, pagecount in string.gmatch(content, "{{Chapter|number=(%d+)|title=([^|]+)|date=([^|]+)|pagecount=(%d+)}}") do
        table.insert(chapters, {number = tonumber(number), title = title, date = date, pagecount = tonumber(pagecount)})
    end

    mw.logObject(chapters)  -- Debug: log the parsed chapters

    return chapters
end

function p.getChapterDetails(chapterTitle, detail)
    local chapters = p.getChaptersList()
    for _, chapter in ipairs(chapters) do
        if chapter.title == chapterTitle then
            mw.logObject(chapter)  -- Debug: log the chapter details
            return chapter[detail]
        end
    end
    return nil
end

function p.getTotalChapters()
    local totalChapters = #p.getChaptersList()
    mw.log("Total chapters: " .. totalChapters)  -- Debug: log the total number of chapters
    return totalChapters
end

function p.getNextChapter(chapterTitle)
    local chapters = p.getChaptersList()
    for i, chapter in ipairs(chapters) do
        if chapter.title == chapterTitle and i < #chapters then
            mw.log("Next chapter: " .. chapters[i + 1].title)  -- Debug: log the next chapter
            return chapters[i + 1].title
        end
    end
    return nil
end

function p.getPreviousChapter(chapterTitle)
    local chapters = p.getChaptersList()
    for i, chapter in ipairs(chapters) do
        if chapter.title == chapterTitle and i > 1 then
            mw.log("Previous chapter: " .. chapters[i - 1].title)  -- Debug: log the previous chapter
            return chapters[i - 1].title
        end
    end
    return nil
end

return p