-- Gamepad Guild Trader
-- Author: @doomvipr
-- lua\TradeHouse.lua: Trade House Features

-- Setup the display format of our Trade House list items.
local function SetupList(isBrowse)

  -- These variables must be returned to the original function as they are required by the game UI.
  return function(control, data, selected, selectedDuringRebuild, enabled, activated)
    ZO_SharedGamepadEntry_OnSetup(control, data, selected, selectedDuringRebuild, enabled, activated)
    local tooExpensive = false
    local priceControl = control:GetNamedChild("Price")
    priceControl:SetColor(1, 1, 1, 1)

    -- Verify that the function is being used to generate Browse List Items.
    if (isBrowse) then

      -- If player doesn't have enough money for the item, color the price text red.
      if (data.purchasePrice > GetCarriedCurrencyAmount(CURT_MONEY)) then
        priceControl:SetColor(1, 0, 0, 1)
      end

    end

    -- Set the purchace price of the item.
    priceControl:SetText(ZO_CurrencyControl_FormatCurrencyAndAppendIcon(data.purchasePrice, true, CURT_MONEY, true))

    -- Display the remaining time that the item is for sale.
    local timeRemainingControl = control:GetNamedChild("TimeRemaining")
    if not data.isGuildSpecificItem then
      timeRemainingControl:SetHidden(false)
      timeRemainingControl:SetText("(" .. zo_strformat(SI_TRADING_HOUSE_BROWSE_ITEM_REMAINING_TIME, ZO_FormatTime(data.timeRemaining, TIME_FORMAT_STYLE_SHOW_LARGEST_UNIT_DESCRIPTIVE, TIME_FORMAT_PRECISION_SECONDS, TIME_FORMAT_DIRECTION_DESCENDING)) .. ")")
    else
      timeRemainingControl:SetHidden(true)
    end

    -- Display Unit Price label.
    local unitPriceControl = control:GetNamedChild("UnitPrice")
    unitPriceControl:SetHidden(false)
    unitPriceControl:SetText(zo_strformat(SI_GGT_TRADEHOUSE_UNITPRICE))

    -- Setup and display unit price value. Value is rounded up to avoid repeating decimals.
    local unitPriceControlValue = control:GetNamedChild("UnitPriceValue")
    unitPriceControlValue:SetHidden(false)
    if (data.stackCount ~= 1) then
      unitPriceControlValue:SetText(zo_strformat("<<1>> |t20:20:esoui/art/currency/gamepad/gp_gold.dds|t", ZO_CurrencyControl_FormatCurrency(math.ceil(data.purchasePrice / data.stackCount), true)))
    else
      -- If the item isnt stack, set text to Not Applicable
      unitPriceControlValue:SetText(zo_strformat(SI_GGT_TRADEHOUSE_NOTAPPLICABLE))
    end
  end
end

-- Ensures GGT_TradingHouse_ItemListRow template is available for use in the Trading House lists
local function FixDataTypes(list, template, isBrowse)
  list:GetList().dataTypes[template] = {
    pool = ZO_ControlPool:New(template, list:GetList().scrollControl, template),
    setupFunction = SetupList(isBrowse),
    parametricFunction = ZO_GamepadMenuEntryTemplateParametricListFunction,
    equalityFunction = function(data1, data2) return data1 == data2 end,
    hasHeader = false
  }
end

-- Replaces the original AddEntryToList function in order to load our custom UI.
function ReplaceAddEntryToList(template)
  return function (self, itemData)
    if itemData then
      local entry = ZO_GamepadEntryData:New(itemData.name, itemData.iconFile)
      entry:InitializeTradingHouseVisualData(itemData)

      -- NOTE: The four numbers at the end of this function setup our list item
      -- spacing so that the list items don't clip each other.
      self:GetList():AddEntry(template, entry, 12, 12, 12, 12)
    end
  end
end

-- Replaces the original BuildList function in order to load our custom UI.
function ReplaceBuildList(template)
  return function(self)
    for i = 1, GetNumTradingHouseListings() do
      local itemData = ZO_TradingHouse_CreateItemData(i, GetTradingHouseListingItemInfo)
      if itemData then
        itemData.name = zo_strformat(SI_TOOLTIP_ITEM_NAME, itemData.name)
        itemData.price = itemData.purchasePrice
        itemData.time = itemData.timeRemaining

        local entry = ZO_GamepadEntryData:New(itemData.name, itemData.iconFile)
        entry:InitializeTradingHouseVisualData(itemData)

        -- NOTE: The four numbers at the end of this function setup our list item
        -- spacing so that the list items don't clip each other.
        self:GetList():AddEntry(template, entry, 12, 12, 12, 12)
      end
    end
  end
end

-- Load our custom Browse Result list.
function GGT.TradeHouse.Browse:Initialize(template)
  local TradeHouseBrowseResults = GAMEPAD_TRADING_HOUSE_BROWSE_RESULTS
  FixDataTypes(TradeHouseBrowseResults, template, true)

  -- Override original function with our custom one, as stated above.
  TradeHouseBrowseResults.AddEntryToList = ReplaceAddEntryToList(template)
end

-- Load our custom Item Listings.
function GGT.TradeHouse.Listings:Initialize(template)
  local TradeHouseListings = GAMEPAD_TRADING_HOUSE_LISTINGS
  FixDataTypes(TradeHouseListings, template, false)

  -- Override original function with our custom one, as stated above.
  TradeHouseListings.BuildList = ReplaceBuildList(template)
end

-- Initialize Trade House UI.
function GGT.TradeHouse:Initialize()
  GGT.TradeHouse.Browse:Initialize("GGT_TradingHouse_ItemListRow")
  GGT.TradeHouse.Listings:Initialize("GGT_TradingHouse_ItemListRow")
end