local GC = select(2, ...)

local Merchant = {}
GC.Merchant = Merchant

local private = {}

-- Wow APIs
local GetItemInfo, GetItemCount, C_Container, GetCoinTextureString =
    GetItemInfo, GetItemCount, C_Container, GetCoinTextureString

--[[------------------------------------------------------------------------
    Event: Merchant window opened
--------------------------------------------------------------------------]]
function Merchant.OnShow(event)
    -- Auto sell gray items
    if GC.GetFromDb("general", "sellGrayItemsToVendor") == true then
        GC.Session.Start(true)
        GC.Debug.Log("Merchant Opened")
        GC.Debug.Log("Auto Sell Grays: |cff00fe00Enabled|r")
        private.SellGrayItems()
    end

    -- Auto repair gear
    if GC.GetFromDb("general", "autoRepairGear") == true then
        GC.Debug.Log("Auto Repair: |cff00fe00Enabled|r")
        private.AutoRepairGear()
    end
end

--[[------------------------------------------------------------------------
    Event: Merchant window closed
--------------------------------------------------------------------------]]
function Merchant.OnClose() GC.Debug.Log("Merchant Closed") end

--[[------------------------------------------------------------------------
    Sell all gray (poor quality) items in bags
--------------------------------------------------------------------------]]
function private.SellGrayItems()
    local totalItemValueOfGrays = 0
    local rarityCounter = 0

    for bag = 0, NUM_BAG_SLOTS do
        for slot = 1, C_Container.GetContainerNumSlots(bag) do
            local itemLink = C_Container.GetContainerItemLink(bag, slot)

            if itemLink ~= nil then
                local _, _, itemID = strfind(itemLink, "item:(%d+):")
                if itemID == nil then
                    GC.Debug.Log("No itemID found for " .. itemLink ..
                                     " in bag slot " .. bag)
                else
                    local _, _, rarity = GetItemInfo(itemID)
                    local itemInfo = GetItemInfo(itemID)
                    local currentItemValue =
                        GC.PriceSources.GetItemValue(itemID, "VendorValue") or 0

                    local iStackCount = GetItemCount(itemInfo)
                    if iStackCount > 1 then
                        currentItemValue = currentItemValue * iStackCount
                    end

                    if rarity == 0 and currentItemValue ~= 0 then
                        rarityCounter = rarityCounter + 1
                        GC.Debug.Log(
                            "selling gray item: " .. itemLink .. " x" ..
                                iStackCount .. ": " ..
                                GetCoinTextureString(currentItemValue))
                        totalItemValueOfGrays =
                            totalItemValueOfGrays + currentItemValue

                        if GC.db.profile.general.sellGrayItemsToVendorVerbose ~=
                            true then
                            GC:Print("Selling " .. itemLink .. " x" ..
                                         iStackCount .. ": " ..
                                         GetCoinTextureString(currentItemValue))
                        end

                        C_Container.UseContainerItem(bag, slot)
                    end
                end
            end
        end
    end

    -- Update vendor sales on UI
    if GC.GetFromDb("display", "showValueSoldToVendor") == true then
        local formattedTotalVendorSoldCurrency =
            GC.Session.GetCurrentSession("vendorSoldCurrencyUI") or 0
        local totalSoldValue = formattedTotalVendorSoldCurrency +
                                   totalItemValueOfGrays or 0
        GC.Debug.Log("totalSoldValue: " .. totalSoldValue)
        GC.Session.SetCurrentSession("vendorSoldCurrencyUI", totalSoldValue)
        GC.Debug.Log("Set Session: " ..
                         GC.Session.GetCurrentSession("vendorSoldCurrencyUI"))

        private.HandleVendorSales(totalSoldValue)
    end

    if rarityCounter > 0 then
        GC:Print("Total Gray Sales: " ..
                     GetCoinTextureString(totalItemValueOfGrays))
    end
end

--[[------------------------------------------------------------------------
    Handle vendor sales currency tracking
--------------------------------------------------------------------------]]
function private.HandleVendorSales(totalSoldValue)
    GC.Debug.Log("handle vendor sales: " .. totalSoldValue)
    local totalVendorSalesCurrency = GC.Session.GetCurrentSession(
                                         "vendorSoldCurrencyUI") or 0
    GC.Debug.Log("total value: " .. totalVendorSalesCurrency)
    GC.Session.SetCurrentSession("vendorSoldCurrencyUI",
                                 totalVendorSalesCurrency)
end

--[[------------------------------------------------------------------------
    Auto-repair all gear at vendor
--------------------------------------------------------------------------]]
function private.AutoRepairGear()
    if CanMerchantRepair() then
        GC.Debug.Log("Merchant can repair")
        local RepairCost = GetRepairAllCost()
        if RepairCost > 0 then
            if GetMoney() >= RepairCost then
                RepairAllItems()
                GC.Debug
                    .Log("Repair cost: " .. GetCoinTextureString(RepairCost))
                GC:Print("Repair cost: " .. GetCoinTextureString(RepairCost))
            end
        end
    end
end

