AuctionatorCancellingFrameMixin = {}

function AuctionatorCancellingFrameMixin:OnLoad()
  Auctionator.Debug.Message("AuctionatorCancellingFrameMixin:OnLoad()")

  self.ResultsListing:Init(self.DataProvider)

  Auctionator.EventBus:Register(self, {
    Auctionator.Cancelling.Events.RequestCancel,
    Auctionator.Cancelling.Events.TotalUpdated,
  })

  self.SearchFilter:HookScript("OnTextChanged", function()
    self.DataProvider:NoQueryRefresh()
  end)
end

function AuctionatorCancellingFrameMixin:RefreshButtonClicked()
  self.DataProvider:QueryAuctions()
end

function AuctionatorCancellingFrameMixin:IsAuctionShown(auctionInfo)
  local searchString = self.SearchFilter:GetText()
  if searchString ~= "" then
    local exact = searchString:match("^\"(.*)\"$")
    local name = string.lower(auctionInfo.searchName)
    if exact then
      return name == exact
    else
      return string.find(name, string.lower(searchString), 1, true)
    end
  else
    return true
  end
end

function AuctionatorCancellingFrameMixin:ReceiveEvent(eventName, ...)
  if eventName == Auctionator.Cancelling.Events.RequestCancel then
    local auctionID = ...
    Auctionator.Debug.Message("Executing cancel request", auctionID)

    local cancelCost = C_AuctionHouse.GetCancelCost(auctionID)
    if cancelCost > 0 then
      Auctionator.Dialogs.ShowMoney(AUCTIONATOR_L_BID_EXISTING_ON_OWNED_AUCTION, cancelCost, ACCEPT, CANCEL, function()
        Auctionator.AH.CancelAuction(auctionID)
        Auctionator.EventBus:RegisterSource(self, "CancellingFramePopupDialog")
          :Fire(self, Auctionator.Cancelling.Events.CancelConfirmed, auctionID)
          :UnregisterSource(self)
      end)
    else
      Auctionator.AH.CancelAuction(auctionID)
      Auctionator.EventBus:RegisterSource(self, "CancellingFrame")
        :Fire(self, Auctionator.Cancelling.Events.CancelConfirmed, auctionID)
    end

    PlaySound(SOUNDKIT.IG_MAINMENU_OPEN)

  elseif eventName == Auctionator.Cancelling.Events.TotalUpdated then
    local totalOnSale, totalPending = ...

    local text = AUCTIONATOR_L_TOTAL_ON_SALE:format(
        GetMoneyString(totalOnSale, true)
      )
    if totalPending > 0 then
      text = text .. " " ..
      AUCTIONATOR_L_TOTAL_PENDING:format(
        GetMoneyString(totalPending, true)
      )
    end

    self.Total:SetText(text)
  end
end
