require "PZAPI/ModOptions"

-- Trap Manager — Native B42 Mod Options
-- Provides a keybind to toggle the window and an hourly auto-refresh toggle.

local TM = {}
TM.MOD_ID           = "TrapManager"             -- unique ModOptions ID
TM.OPT_OPENKEY_ID   = "openKey"                 -- keybind option id
TM.OPT_HOURLY_ID    = "hourlyAutoRefresh"       -- tickbox option id
TM.DEFAULT_KEY      = Keyboard.KEY_DIVIDE       -- default: Numpad /
TM.DEFAULT_HOURLY   = true                      -- default: enabled
TM.OPT_VERBOSE_ID    = "verboseTooltips"   -- tickbox option id
TM.DEFAULT_VERBOSE   = true                -- default: enabled

---------------------------------------------------------------------
-- Columns to show after pressing "Reset" (order == header order)
-- Keys MUST match TrapManagerWindow:buildColumnConfig()
---------------------------------------------------------------------
TM.RESET_COLUMNS = {
    -- { id,               key,              nameKey,                   default }
    { id="col_showhide",   key="showhide",     nameKey="UI_TM_Col_ShowHide",   default=true  }, -- Show
    { id="col_number",     key="name",         nameKey="UI_TM_Col_Number",     default=true  }, -- #
    { id="col_distance",   key="distance",     nameKey="UI_TM_Col_Distance",   default=true  }, -- Distance
    { id="col_chunks",     key="chunks",       nameKey="UI_TM_Col_Chunks",     default=true  }, -- Chunks
    { id="col_pre",        key="eligible",     nameKey="UI_TM_Col_Precond",    default=true  }, -- Pre.
    { id="col_animal",     key="animal",       nameKey="UI_TM_Col_Animal",     default=true  }, -- Animal
    { id="col_aliveHour",  key="aliveHour",    nameKey="UI_TM_Col_AliveHour",  default=false }, -- Hours
    { id="col_trap",       key="trapType",     nameKey="UI_TM_Col_Trap",       default=true  }, -- Trap
    { id="col_bait",       key="bait",         nameKey="UI_TM_Col_Bait",       default=true  }, -- Bait
    { id="col_dus",        key="daysUntilStale", nameKey="UI_TM_Col_DUS",      default=false }, -- Days
    { id="col_skill",      key="skill",        nameKey="UI_TM_Col_Skill",      default=true  }, -- Skill
    { id="col_player",     key="player",       nameKey="UI_TM_Col_Player",     default=false }, -- Player
    { id="col_zone",       key="zone",         nameKey="UI_TM_Col_Zone",       default=true  }, -- Zone
    { id="col_chance",     key="chance",       nameKey="UI_TM_Col_Chance",     default=true  }, -- Chance
}

---------------------------------------------------------------------
-- Persistent defaults for "Reset" (stored in TrapManager_ResetCols.ini)
-- We keep a per-key boolean map. If file is missing/corrupt, fall back to table defaults.
---------------------------------------------------------------------
local TM_RESET_FILE = "TrapManager_ResetCols.ini"
local _tmResetByKey = nil  -- lazy-initialized table: key -> boolean

local function _tmResetEnsureDefaults()
    _tmResetByKey = {}
    for _, c in ipairs(TM.RESET_COLUMNS) do
        _tmResetByKey[c.key] = (c.default == true)
    end
end

function TM_LoadResetPrefs()
    _tmResetEnsureDefaults()
    local r = getFileReader(TM_RESET_FILE, true)
    if not r then return end
    while true do
        local line = r:readLine()
        if not line then r:close(); break end
        -- accept "resetcol|<key>|<true/false>"  OR  "<key>=<true/false>"
        local key, val = line:match("^resetcol|([^|]+)|(%a+)$")
        if not key then key, val = line:match("^([^=]+)=(%a+)$") end
        if key and val then
            local b = (string.lower(val) == "true")
            if _tmResetByKey[key] ~= nil then
                _tmResetByKey[key] = b
            end
        end
    end
end

function TM_SaveResetPrefs()
    if not _tmResetByKey then _tmResetEnsureDefaults() end
    local w = getFileWriter(TM_RESET_FILE, true, false)
    for _, c in ipairs(TM.RESET_COLUMNS) do
        local key = c.key
        local val = (_tmResetByKey[key] and "true") or "false"
        w:write(string.format("resetcol|%s|%s\r\n", key, val))
    end
    w:close()
end

function TM_GetResetPref(colKey)
    if not _tmResetByKey then TM_LoadResetPrefs() end
    local v = _tmResetByKey[colKey]
    if v == nil then
        -- safety fallback to table defaults
        for _, c in ipairs(TM.RESET_COLUMNS) do
            if c.key == colKey then return (c.default == true) end
        end
        return true
    end
    return v
end

function TM_SetResetPref(colKey, value)
    if not _tmResetByKey then TM_LoadResetPrefs() end
    if _tmResetByKey[colKey] == nil then return end
    _tmResetByKey[colKey] = (value == true)
    TM_SaveResetPrefs()
end

function TM_ToggleResetPref(colKey)
    TM_SetResetPref(colKey, not TM_GetResetPref(colKey))
end

-- Compatibility shim used by the window's Reset button:
function TM_ShouldShowColumnOnReset(colKey)
    return TM_GetResetPref(colKey)
end

-- Optional: factory defaults
function TM_ResetDefaultColumnsToFactory()
    _tmResetEnsureDefaults()
    TM_SaveResetPrefs()
end
----------------------------------------------------------------------

-- Returns default visibility for a given column key (safety fallback)
local function _defaultForKey(key)
    for _, c in ipairs(TM.RESET_COLUMNS) do
        if c.key == key then return c.default end
    end
    return true
end

------------------------------------------------------------
-- Create or fetch our Mod Options page and options
------------------------------------------------------------
local function TM_InitOptions()
	-- Create (if missing) or fetch our options page
    local options = PZAPI.ModOptions:getOptions(TM.MOD_ID)
    if not options then
        options = PZAPI.ModOptions:create(TM.MOD_ID, getText("UI_TM_Title"))
    end

	-- Helpers: add-or-skip so this is safe across updates
    local function ensureKeyBind(id, label, defaultKey, tooltip)
        if not options:getOption(id) then
            options:addKeyBind(id, label, defaultKey, tooltip)
        end
    end
    local function ensureTick(id, label, defaultVal, tooltip)
        if not options:getOption(id) then
            options:addTickBox(id, label, defaultVal, tooltip)
        end
    end

	-- Keybind to open/close the window
    ensureKeyBind(TM.OPT_OPENKEY_ID, getText("UI_TM_OpenClose"), TM.DEFAULT_KEY, getText("UI_TM_OpenClose_Tooltip"))
	-- Hourly auto-refresh (applies while window is open)
    ensureTick(TM.OPT_HOURLY_ID, getText("UI_TM_AutoHourly"), TM.DEFAULT_HOURLY, getText("UI_TM_AutoHourly_Tooltip"))
	-- Verbose header tooltips
    ensureTick(TM.OPT_VERBOSE_ID, getText("UI_TM_Opt_VerboseTips"), TM.DEFAULT_VERBOSE, getText("UI_TM_Opt_VerboseTips_Tooltip"))
end

------------------------------------------------------------
-- Accessors for current option values
------------------------------------------------------------
function TM_GetOpenKey()
    local options = PZAPI.ModOptions:getOptions(TM.MOD_ID)
    if options then
        local opt = options:getOption(TM.OPT_OPENKEY_ID)
        if opt and opt.getValue then
            local v = opt:getValue()
            if type(v) == "number" then return v end
        end
    end
    return TM.DEFAULT_KEY
end

-- Returns true if hourly auto-refresh is enabled
function TM_IsHourlyEnabled()
    local options = PZAPI.ModOptions:getOptions(TM.MOD_ID)
    if options then
        local opt = options:getOption(TM.OPT_HOURLY_ID)
        if opt and opt.getValue then
            local v = opt:getValue()
            if type(v) == "boolean" then return v end
        end
    end
    return TM.DEFAULT_HOURLY
end

-- Returns true when explanatory (verbose) header tooltips are enabled
function TM_AreVerboseTipsEnabled()
    local options = PZAPI.ModOptions:getOptions(TM.MOD_ID)
    if options then
        local opt = options:getOption(TM.OPT_VERBOSE_ID)
        if opt and opt.getValue then
            local v = opt:getValue()
            if type(v) == "boolean" then return v end
        end
    end
    return TM.DEFAULT_VERBOSE
end

---------------------------------------------------------------------
-- In-place: applies Reset visibility to a columnConfig array:
--   for each col -> col.visible = TM_ShouldShowColumnOnReset(col.key)
-- Usage from Trap Manager window:
--   TM_ApplyResetColumnsVisibility(grid:getColumns()); grid:refresh()
---------------------------------------------------------------------
function TM_ApplyResetColumnsVisibility(columnConfig)
    if not columnConfig then return end
    for _, col in ipairs(columnConfig) do
        if col and col.key then
            col.visible = TM_ShouldShowColumnOnReset(col.key)
        end
    end
end

------------------------------------------------------------
-- Lifecycle: build page and load persisted values
------------------------------------------------------------
Events.OnGameBoot.Add(function()
    TM_InitOptions()
    TM_LoadResetPrefs()          -- load our Reset defaults
    PZAPI.ModOptions:load()      -- load ModOptions (for keybind/hourly-refresh/tooltips)
end)

------------------------------------------------------------
-- Hotkey: open/close window (reads key each time)
------------------------------------------------------------
Events.OnKeyPressed.Add(function(key)
    if key == TM_GetOpenKey() then
        if TrapManagerWindow and TrapManagerWindow.OnOpenPanel then
            TrapManagerWindow.OnOpenPanel()
        end
    end
end)
