local _,ns = ...
local L = ns.L

local f = CreateFrame("Frame")

local function isInImportantTask()
    if IsInGroup(LE_PARTY_CATEGORY_INSTANCE) then
        return true
    end
    if IsInActiveWorldPVP() then
        return true
    end
    local inInstance, instanceType = IsInInstance()
    if inInstance and instanceType == "neighborhood" then
        return false
    elseif inInstance and instanceType == "none" then
        return false
    -- scenario son los delves (prodfundidades) puede que otras cosas
    -- elseif inInstance and instanceType == "scenario" then
    --     return false
    elseif inInstance then
        return true
    end
    return false
end

f:RegisterEvent("TOKEN_MARKET_PRICE_UPDATED")
f:SetScript("OnEvent", function()
    
    if not AutoScrap_GlobalSettings.WowTokenListenerGroupInstance and isInImportantTask() then
        return
    end
    local price = C_WowTokenPublic.GetCurrentMarketPrice()
    if price then
        price = math.floor(price / 10000)
        ns.actualizarPrecioWowTokenCombinedBags(price)
        --local precio = GetMoneyString(price) -- no usar esto porque añade un icono de gold
        if AutoScrap_GlobalSettings.lastWowTokenPrice == 0 then
            AutoScrap_GlobalSettings.lastWowTokenPrice = price
        else
            if math.abs(AutoScrap_GlobalSettings.lastWowTokenPrice - price) > AutoScrap_GlobalSettings.WowTokenPriceThreshold then
                AutoScrap_GlobalSettings.lastWowTokenPrice = price
                ns.mostrarWowTokenPanel(price)
            end
        end

        -- ns.mostrarWowTokenPanel(math.floor(price / 10000))
    end
end)

local elapsed = 20
local function listener (self, e)
    elapsed = elapsed + e
    if elapsed > 35 then
        elapsed = 0
        if not AutoScrap_GlobalSettings.WowTokenListenerGroupInstance and isInImportantTask() then
            return
        end
        C_WowTokenPublic.UpdateMarketPrice()
    end
end

function ns.runWowTokenListener()
    f:SetScript("OnUpdate", listener)
end