-- Based on patch:
-- https://github.com/sebdelsol/KOReader.patches/blob/main/2--ui-font.lua by @sebdelsol

local Device = require("device")
local Font = require("ui/font")
local FontList = require("fontlist")
local Setting = require("lib/setting")
local TitleBar = require("ui/widget/titlebar")
local UIManager = require("ui/uimanager")
local cre = require("document/credocument"):engineInit()
local nf_icons = require("lib/nf_icons")

local UIFontName = Setting("ui_font_name", "Noto Sans", true)
local UIFontEnabled = Setting("ui_font_enabled", true, true)
local SystemFonts = Setting("system_fonts", false, true)

local font_list
local fonts
local to_be_replaced
local font_type = { regular = "NotoSans-Regular.ttf", bold = "NotoSans-Bold.ttf" }

local function get_bold_path(path_regular)
    if not path_regular then return nil end
    -- Try "Font-Regular.ext" -> "Font-Bold.ext"
    local path_bold, n_repl = path_regular:gsub("%-Regular%.", "-Bold.", 1)
    if n_repl > 0 then return path_bold end
    -- Try "Font.ext" -> "Font-Bold.ext"
    path_bold, n_repl = path_regular:gsub("(%.)([^.]+)$", "-Bold.%2", 1)
    return n_repl > 0 and path_bold
end

local function refresh_titlebar_faces()
    -- These are the four class-level default font types in TitleBar.
    -- Re-fetching them forces Font to resolve the new fontmap path and cache
    -- a face under the new hash, then we replace the class default.
    local slots = {
        { field = "title_face_fullscreen",     face = "smalltfont" },
        { field = "title_face_not_fullscreen", face = "x_smalltfont" },
        { field = "subtitle_face",             face = "xx_smallinfofont" },
        { field = "info_text_face",            face = "x_smallinfofont" },
    }
    for _, s in ipairs(slots) do
        local ok_f, face = pcall(Font.getFace, Font, s.face)
        if ok_f and face then
            TitleBar[s.field] = face
        end
    end
end

local sizemap = {
    cfont = 24,
    tfont = 26,
    smalltfont = 24,
    x_smalltfont = 22,
    ffont = 20,
    smallffont = 15,
    largeffont = 25,
    pgfont = 20,
    scfont = 20,
    rifont = 16,
    hpkfont = 20,
    hfont = 24,
    infont = 22,
    smallinfont = 16,
    infofont = 24,
    smallinfofont = 22,
    smallinfofontbold = 22,
    x_smallinfofont = 20,
    xx_smallinfofont = 18,
}

-- Override the font for widgets that have already been loaded
local function apply_font_to_widgets()
    local font_name = fonts[UIFontName.get()].regular

    local ok_bd, ButtonDialog = pcall(require, "ui/widget/buttondialog")
    if ok_bd and ButtonDialog then
        if ButtonDialog.title_face then
            local orig_size = ButtonDialog.title_face.orig_size or sizemap.x_smalltfont
            ButtonDialog.title_face = Font:getFace(font_name, orig_size)
        end
        if ButtonDialog.info_face then
            local orig_size = ButtonDialog.info_face.orig_size or sizemap.infont
            ButtonDialog.info_face = Font:getFace(font_name, orig_size)
        end
    end

    local ok_cb, ConfirmBox = pcall(require, "ui/widget/confirmbox")
    if ok_cb and ConfirmBox then
        local orig_size = ConfirmBox.face.orig_size or sizemap.infont
        ConfirmBox.face = Font:getFace(font_name, orig_size)
    end

    local ok_mcb, MultiConfirmBox = pcall(require, "ui/widget/multiconfirmbox")
    if ok_mcb and MultiConfirmBox then
        local orig_size = MultiConfirmBox.face.orig_size or sizemap.infont
        MultiConfirmBox.face = Font:getFace(font_name, orig_size)
    end

    local ok_im, InfoMessage = pcall(require, "ui/widget/infomessage")
    if ok_im and InfoMessage then
        local def_face = Font:getFace("infofont")
        local orig_size = def_face.orig_size or sizemap.infont
        InfoMessage.face = Font:getFace(font_name, orig_size)
    end

    local ok_id, InputDialog = pcall(require, "ui/widget/inputdialog")
    if ok_id and InputDialog then
        local orig_size = InputDialog.input_face.orig_size or sizemap.smallinfont
        InputDialog.input_face = Font:getFace(font_name, orig_size)
    end
end

local function apply_font(name)
    name = name or UIFontName.get()
    if not UIFontEnabled.get() or not fonts[name] then return end
    for font, typ in pairs(to_be_replaced) do
        Font.fontmap[font] = fonts[name][typ]
    end

    refresh_titlebar_faces()
    apply_font_to_widgets()
end

local function set_font(name)
    if not fonts[name] then return end
    local changed = name ~= UIFontName.get()
    UIFontName.set(name)
    apply_font(name)
    return changed
end

local function init(font_name)
    font_list = {}
    fonts = {}
    to_be_replaced = {}

    local path_exists = {}
    for _, font in ipairs(FontList.fontlist) do
        path_exists[font] = true
    end

    -- Get fonts from CRE font list
    for _, name in ipairs(cre.getFontFaces()) do
        local path_regular = cre.getFontFaceFilenameAndFaceIndex(name)
        if path_regular and path_exists[path_regular] then
            local path_bold = get_bold_path(path_regular)
            local bold_exists = path_exists[path_bold]

            table.insert(font_list, name)
            -- Add both regular and bold versions if they exist, otherwise default to regular
            if bold_exists then
                fonts[name] = { regular = path_regular, bold = path_bold }
            else
                fonts[name] = { regular = path_regular, bold = path_regular }
            end
        end
    end

    local type_font = {}
    for typ, font in pairs(font_type) do
        type_font[font] = typ
    end
    for name, font in pairs(Font.fontmap) do
        to_be_replaced[name] = type_font[font]
    end

    apply_font(font_name)
end

init()

-- Menu
local _ = require("gettext")
local T = require("ffi/util").template

local function font_face_menu()
    return {
        text_func = function()
            return T(nf_icons.label(nf_icons.FONT, _("Font: %1")), UIFontEnabled.get() and UIFontName.get() or "default")
        end,
        sub_item_table_func = function()
            local items = {
                {
                    text = "Enable font replacement",
                    checked_func = UIFontEnabled.get,
                    callback = function()
                        UIFontEnabled.toggle()
                        apply_font()
                        UIManager:askForRestart(_("Restart to fully apply the UI font change."))
                    end,
                    separator = true,
                },
            }
            -- Add option for toggling system fonts on supported platforms
            if Device:isAndroid() or Device:isDesktop() or Device:isEmulator() or Device:isPocketBook() then
                items[1].separator = nil
                table.insert(items, {
                    text = "Enable system fonts",
                    checked_func = SystemFonts.get,
                    callback = function()
                        SystemFonts.toggle()
                        UIManager:askForRestart()
                    end,
                    separator = true,
                })
            end
            for i, name in ipairs(font_list) do
                table.insert(items, {
                    text = T(name .. " %1", fonts[name].regular == fonts[name].bold and "(no bold)" or ""),
                    font_func = function(size)
                        return Font:getFace(fonts[name].regular, size)
                    end,
                    checked_func = function()
                        return name == UIFontName.get()
                    end,
                    radio = true,
                    callback = function()
                        if set_font(name) then
                            UIManager:askForRestart(_("Restart to fully apply the UI font change."))
                        end
                    end,
                })
            end
            return items
        end
    }
end

return font_face_menu
