local select, hooksecurefunc = select, hooksecurefunc
local CreateFrame, GetMerchantNumItems, GetMerchantItemInfo = CreateFrame, GetMerchantNumItems, GetMerchantItemInfo

local cache = {}
local function checkItem(link)
  if not link then return end
  local id = link:match('item:(%d+)')
  if cache[id] then return cache[id] end

  GameTooltip:SetOwner(this, "ANCHOR_NONE")
  GameTooltip:SetHyperlink(link)
  local alreadyKnown
  --local lines = GameTooltip:NumLines() < 6 and GameTooltip:NumLines() or 6
  for i = 2, GameTooltip:NumLines() do
    local text = _G["GameTooltipTextLeft"..i]:GetText()
    if text == ITEM_SPELL_KNOWN then
      alreadyKnown = true
      break
    end
  end
  GameTooltip:Hide()
  cache[id] = alreadyKnown
  return alreadyKnown
end

hooksecurefunc("MerchantFrame_UpdateMerchantInfo", function()
  local numMerchantItems = GetMerchantNumItems()

  for i=1, MERCHANT_ITEMS_PER_PAGE do
    local index = (MerchantFrame.page - 1) * MERCHANT_ITEMS_PER_PAGE + i
    if index <= numMerchantItems then
      local isUsable = select(6, GetMerchantItemInfo(index))
      local itemButton = _G["MerchantItem"..i.."ItemButton"]
      local merchantButton = _G["MerchantItem"..i]
      if isUsable and checkItem(itemButton.link) then
        SetItemButtonNameFrameVertexColor(merchantButton, 0, .5, 0)
        SetItemButtonSlotVertexColor(merchantButton, 0, .5, 0)
        SetItemButtonTextureVertexColor(itemButton, 0, .5, 0)
        SetItemButtonNormalTextureVertexColor(itemButton, 0, .5, 0)
      end
    end
  end
end)
