local re = re
local sdk = sdk
local d2d = d2d
local imgui = imgui
local log = log
local json = json
local draw = draw
local require = require
local tostring = tostring
local pairs = pairs
local ipairs = ipairs
local math = math
local string = string
local table = table
local type = type

local Core = require("_CatLib")
local Debug = require("_CatLib.debug")
local Core = require("_CatLib")
local CONST = require("_CatLib.const")

local mod = Core.NewMod("Auto Cooldown Mantle")

if mod.Config.SendNotification == nil then
    mod.Config.SendNotification = true
end

local NOTIFICATIONS = {
    [CONST.LanguageType.English] = "Mantle cooldown",
    [CONST.LanguageType.TraditionalChinese] = "衣装已刷新",
    [CONST.LanguageType.SimplifiedChinese] = "衣装已刷新",
}

local CooldownRequestState = false

local function RequestCooldown()
    CooldownRequestState = true
end

Core.HookFunc("app.mcActiveSkillController", "updateMain()",
function (args)
    if not CooldownRequestState then return end

    ---@type app.mcActiveSkillController
    local this = sdk.to_managed_object(args[2])
    if not this then return end

    local hunter = this._Hunter
    if not hunter or not hunter:get_IsMaster() then
        return
    end

    local NeedRefresh = CooldownRequestState
    CooldownRequestState = false
    local Refreshed = false

    local skills = this:get_ActiveSkills()
    Core.ForEach(skills, function (skill, i)
        if NeedRefresh then
            -- skill:resetCDTime() -- doesnt work wtf
            -- skill:crearTime() -- no work
            if (not skill:get_IsUse()) and skill:get_Timer() > 0 then
                skill:setTime(0)
                Refreshed = true
            end
        end
    end)

    if Refreshed then
        if mod.Config.SendNotification then
            local lang = Core.GetLanguage()
            if not NOTIFICATIONS[lang] then
                lang = CONST.LanguageType.English
            end
            Core.SendMessage(NOTIFICATIONS[lang])
        end
    end
end)

-- TODO：缺点：如果玩家身上穿着过期的则不会刷新

Core.OnAcceptQuest(function ()
    RequestCooldown()
end)

Core.OnQuestEnd(function ()
    RequestCooldown()
end)

mod.Menu(function ()
	local configChanged = false
    local changed

    changed, mod.Config.SendNotification = imgui.checkbox("Send Notification", mod.Config.SendNotification)
    configChanged = configChanged or changed

    if imgui.button("Apply Refresh") then
        RequestCooldown()
    end

    return configChanged
end)
