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

ns.itemCachedPrice = {}

local function crearTabla (valorMercado)
    return {TSMprice = valorMercado}
end

function ns.getItemCachedPrice(itemID)
    if not itemID then
        return
    end
    if ns.itemCachedPrice[itemID] then
        --print ("devuelvo el precio existente",itemID,ns.itemCachedPrice[itemID]["TSMprice"])
        --return ns.itemCachedPrice[itemID]["TSMprice"]
    else
        if itemID == 82800 or itemID == 180653 then -- pets and item de hacer míticas da problemas con el itemlink y no se venden xk no da itemlink o es una jaula y no la pet.
            ns.itemCachedPrice[itemID] = crearTabla(nil)
        else
            if TSM_API and TSM_API.GetCustomPriceValue then
                local valorMercadoComparacion
                local skip = false
                if not AutoScrap_CharSettings.usar2Mercados then
                    valorMercadoComparacion = TSM_API.GetCustomPriceValue(AutoScrap_CharSettings.TSM_mercado, "i:" .. itemID)
                    if not valorMercadoComparacion then
                        skip = true
                    end
                else
                    local valordbmarket = TSM_API.GetCustomPriceValue("dbmarket", "i:" .. itemID)
                    local valordbregionmarketavg = TSM_API.GetCustomPriceValue("dbregionmarketavg", "i:" .. itemID)
                    
                    if not valordbmarket and not valordbregionmarketavg then
                        skip = true
                    elseif not valordbmarket then
                        valorMercadoComparacion = valordbregionmarketavg
                    elseif not valordbregionmarketavg then
                        valorMercadoComparacion = valordbmarket
                    else
                        if  valordbmarket > valordbregionmarketavg  then
                            valorMercadoComparacion = valordbmarket
                        else
                            valorMercadoComparacion = valordbregionmarketavg
                        end
                    end
                end
                if skip then
                    ns.itemCachedPrice[itemID] = crearTabla(nil)
                    --print ("añado",itemID,ns.itemCachedPrice[itemID]["TSMprice"])
                else
                    ns.itemCachedPrice[itemID] = crearTabla(valorMercadoComparacion)
                    --print ("añado",itemID,ns.itemCachedPrice[itemID]["TSMprice"])
                end
            else
                ns.itemCachedPrice[itemID] = crearTabla(nil)
            end
        end
    end
    return ns.itemCachedPrice[itemID]["TSMprice"]
end

function ns.clearItemCachedPrice()
    --print("borro todo")
    ns.itemCachedPrice = {}
end