local ldb = LibStub:GetLibrary("LibDataBroker-1.1")

if ldb then
  local feed = ldb:NewDataObject("QuestHelper2", {
    type = "data source",
    icon = "Interface\\AddOns\\QuestHelper2\\Icons\\LDBIcon.tga",
    label = QUESTS_LABEL,
    text = "?/?"
  })
  
  local function recountQuests()
    local quests = select(2, GetNumQuestLogEntries())
    
    if quests == 0 then
      feed.text = QUESTLOG_NO_QUESTS_TEXT
    else
      feed.text = quests .. "/" .. MAX_QUESTLOG_QUESTS
    end
  end
  
  _G.QuestHelper2.onQuestAdd(recountQuests)
  _G.QuestHelper2.onQuestRemove(recountQuests)
  
  local indent, order = {}, {}
  
  function feed:OnClick(button)
    if button == "RightButton" then
      _G.QuestHelper2.showMainMenu(self, 0, 0)
    else
      _G.QuestHelper2.openConfig()
    end
  end
  
  function feed:OnTooltipShow()
    local lines = 0
    
    local quests, daily = select(2, GetNumQuestLogEntries()), GetDailyQuestsCompleted()
    
    local title = quests == 0 and QUESTLOG_NO_QUESTS_TEXT or QUEST_LOG_COUNT_TEMPLATE:format("|cffffffff", quests, MAX_QUESTLOG_QUESTS)
    
    if daily > 0 then
      self:AddDoubleLine(title, QUEST_LOG_DAILY_COUNT_TEMPLATE:format(daily, GetMaxDailyQuests()), 1, .82, 0, 1, .82, 0)
    else
      self:AddLine(title, 1, .82, 0)
    end
    
    table.wipe(order)
    
    for i, obj in ipairs(_G.QuestHelper2.route) do
      order[i] = obj
    end
    
    _G.QuestHelper2.sortObjectivesByQuest(order, indent)
    
    for i, obj in ipairs(order) do
      local indent = indent[obj]
      
      if indent == 0 and lines > 25 then
        -- I think that's enough garbage.
        break
      elseif indent == 0 then
        -- Create a small spacer.
        self:AddLine(" ")
      end
      
      local r, g, b = 1, 1, 1
      if obj.root then r, g, b = 1, .82, 0 end
      
      local text = ("    "):rep(indent)..obj.text
      local progress = obj.formatted_progress
      
      if progress == "" then
        self:AddLine(text, r, g, b)
      else
        self:AddDoubleLine(text, progress, r, g, b, 1, 1, 1)
      end
      
      lines = lines + 1
    end
  end
  
  --[[
  
  -- I don't think this is necessary; and for the one AddOn I tried (DockingStation); this disabled its ability to scale the tooltips.
  function feed:OnEnter()
    GameTooltip:SetOwner(self, "ANCHOR_NONE")
    GameTooltip:SetPoint("TOPLEFT", self, "BOTTOMLEFT")
    GameTooltip:ClearLines()
    feed.OnTooltipShow(GameTooltip)
    GameTooltip:Show()
  end
  
  function feed:OnLeave()
    GameTooltip:Hide()
  end]]
end
