local GC = select(2, ...)

local PriceSources = {}
GC.PriceSources = PriceSources

-- External globals
local OEMarketInfo = OEMarketInfo
local BlizzardVendorSell = 1

-- Wow APIs
local GetItemInfo, StaticPopupDialogs, StaticPopup_Show = GetItemInfo,
                                                          StaticPopupDialogs,
                                                          StaticPopup_Show
local OKAY = OKAY

--[[------------------------------------------------------------------------
    Get available price sources from loaded addons
--------------------------------------------------------------------------]]
function PriceSources.GetAvailable()
    local priceSources = {}

    -- TSM
    if GC.TSM.IsTSMLoaded() then
        priceSources = GC.TSM.GetAvailablePriceSources() or {}
    end

    -- OE (OribosExchange)
    if OEMarketInfo then
        priceSources["region"] = "OE: Median All Realms in Region"
    end

    -- Blizzard vendor price
    if BlizzardVendorSell == 1 then
        priceSources["VendorValue"] = "Bliz: Vendor price"
    end

    -- Auctionator
    if (C_AddOns.IsAddOnLoaded("Auctionator")) and Auctionator and
        Auctionator.API and Auctionator.API.v1 and
        Auctionator.API.v1.RegisterForDBUpdate then
        priceSources["Auctionator"] = "AN: Auctionator"
    end

    return priceSources
end

--[[------------------------------------------------------------------------
    Validate and prepare price sources on addon enable
--------------------------------------------------------------------------]]
function PriceSources.Prepare()
    GC.Debug.Log("PreparePricesources()")

    local priceSources = PriceSources.GetAvailable() or {}

    -- No price sources available at all
    if GC.Util.tablelength(priceSources) == 0 then
        StaticPopupDialogs["LA_NO_PRICESOURCES"] = {
            text = "|TInterface\\AddOns\\GallywixCoins\\Media\\logo.tga:32:32:0:0|t |cffffd100GallywixCoins|r\n\n|cffff0000Attention!|r Missing pricing data. Please install an addon like |cffffff00Auctionator|r or |cffffff00TradeSkillMaster|r to track your earnings.",
            button1 = OKAY,
            timeout = 0,
            whileDead = true,
            hideOnEscape = true
        }
        StaticPopup_Show("LA_NO_PRICESOURCES")

        GC:Print("|cffff0000Disabled.|r No price source found. Please install a pricing addon.")
        GC.SetGallywixCoinsDisabled(true)
        return
    end

    -- Validate current price source selection
    local priceSource = GC.GetFromDb("pricesource", "source")

    if priceSource == "Custom" then
        local isValid = GC.TSM.ParseCustomPrice(
                            GC.GetFromDb("pricesource", "customPriceSource"))
        if not isValid then
            StaticPopupDialogs["LA_INVALID_CUSTOM_PRICESOURCE"] = {
                text = "|cffff0000Attention!|r You have selected 'Custom' as price source but your formular is invalid (see TSM documentation for detailed custom price source informations).\n\n" ..
                    (GC.GetFromDb("pricesource", "customPriceSource") or
                        "-empty-"),
                button1 = OKAY,
                timeout = 0,
                whileDead = true,
                hideOnEscape = true
            }
            StaticPopup_Show("LA_INVALID_CUSTOM_PRICESOURCE")
        end
    else
        if not priceSources[priceSource] then
            StaticPopupDialogs["LA_INVALID_CUSTOM_PRICESOURCE"] = {
                text = "|TInterface\\AddOns\\GallywixCoins\\Media\\logo.tga:32:32:0:0|t |cffffd100GallywixCoins|r\n\n|cffff0000Attention!|r Your selected price source is no longer valid (maybe due to a missing/disabled addon). Please select a new one in the options menu.",
                button1 = OKAY,
                timeout = 0,
                whileDead = true,
                hideOnEscape = true
            }
            StaticPopup_Show("LA_INVALID_CUSTOM_PRICESOURCE")
        end
    end

    GC.availablePriceSources = priceSources
end

--[[------------------------------------------------------------------------
    Get item value based on the selected/requested price source
--------------------------------------------------------------------------]]
function PriceSources.GetItemValue(itemID, priceSource)
    if priceSource == "VendorValue" then
        -- "VendorValue" is the native Blizzard-only source ("BLIZ: Vendor price")
        return select(11, GetItemInfo(itemID)) or 0

    elseif priceSource == "region" then
        local priceInfo = {}
        OEMarketInfo(itemID, priceInfo)
        return priceInfo[priceSource]

    elseif priceSource == "Auctionator" then
        return Auctionator.API.v1.GetAuctionPriceByItemID(
                   "GallywixCoins", itemID)

    else
        -- All TSM price source keys go through TSM, including "VendorSell"
        -- ("VendorSell" = "TSM: VendorSell", NOT the Blizzard vendor API)
        return GC.TSM.GetItemValue(itemID, priceSource)
    end
end

--[[------------------------------------------------------------------------
    Resolve effective price source for an item (handles class-based overrides)
--------------------------------------------------------------------------]]
function PriceSources.ResolveForItem(itemID, basePriceSource)
    local priceSource = basePriceSource

    if priceSource == "Custom" then
        priceSource = GC.GetFromDb("pricesource", "customPriceSource")
        GC.Debug.Log("CP here: " .. tostring(priceSource))
    end

    -- Class-based price source overrides
    if GC.db.profile.general.useSubClasses == true then
        local class = select(6, GetItemInfo(itemID)) or 0
        local classOverrides = {
            ["Armor"] = {
                enabled = GC.db.profile.classTypeArmor,
                source = GC.db.profile.classTypeArmorPriceSource
            },
            ["Consumable"] = {
                enabled = GC.db.profile.classTypeConsumable,
                source = GC.db.profile.classTypeConsumablePriceSource
            },
            ["Recipe"] = {
                enabled = GC.db.profile.classTypeRecipe,
                source = GC.db.profile.classTypeRecipePriceSource
            },
            ["Tradeskill"] = {
                enabled = GC.db.profile.classTypeTradeskill,
                source = GC.db.profile.classTypeTradeskillPriceSource
            },
            ["Weapon"] = {
                enabled = GC.db.profile.classTypeWeapon,
                source = GC.db.profile.classTypeWeaponPriceSource
            },
            ["Quest"] = {
                enabled = GC.db.profile.classTypeQuest,
                source = GC.db.profile.classTypeQuestPriceSource
            }
        }

        local override = classOverrides[class]
        if override and override.enabled == true then
            priceSource = override.source
            GC.Debug.Log(class .. " price source: " .. tostring(priceSource))
        end
    end

    return priceSource
end

