--[[ FuBar_OutfitterFu - FuBar support for Outfitter ]]--

-- create the plugin object and configure
local VERSION = tonumber(string.find(("$Revision: 36749 $"),"%d+"))
OutfitterFu = AceLibrary("AceAddon-2.0"):new("AceDB-2.0", "AceEvent-2.0", "AceConsole-2.0", "FuBarPlugin-2.0")
local OutfitterFu, self = OutfitterFu, OutfitterFu
OutfitterFu.version = "r" .. VERSION
OutfitterFu.revision = VERSION
OutfitterFu.date = string.find("$Date: 2007-05-24 12:17:52 -0400 (Thu, 24 May 2007) $","%d%d%d%d%-%d%d%-%d%d")
OutfitterFu.hasIcon = "Interface\\AddOns\\Outfitter\\Textures\\Icon"
OutfitterFu.clickableTooltip = true

-- locals for library access
local Tablet = AceLibrary("Tablet-2.0")
local L = AceLibrary("AceLocale-2.2"):new("FuBar_OutfitterFu")

-- locals for static properties
local BANKED_FONT_COLOR = {r = 0.25, g = 0.2, b = 1.0}
local BANKED_FONT_COLOR_CODE = '|cff4033ff'
local textLengthLowerBound = 4
local textLengthUpperBound = 40

OutfitterFu:RegisterDB("OutfitterFuDB")
OutfitterFu:RegisterDefaults('profile', {
   settings = {
      hiddenCategories = {},
      hideMissing = false,
      removePrefixes = false,
      maxTextLength = textLengthUpperBound,
   },
})

-- event hook registered with Outfitter
function OutfitterFu_OutfitEvent(pEvent, pOutfitName, pOutfit)
   OutfitterFu:Update()
end

-- define options context menu
OutfitterFu.OnMenuRequest = {
   type = 'group',
   args = {
      hideMissing = {
         order = 10,
         name = L["Hide missing"],
         desc = L["Hide outfits with missing items."],
         type = 'toggle',
         get = "HideMissing",
         set = "SetHideMissing",
      },
      removePrefixes = {
         order = 20,
         name = L["Remove prefixes"],
         desc = L["Remove outfit name prefixes to shorten the text displayed in FuBar."],
         type = 'toggle',
         get = "RemovePrefixes",
         set = "SetRemovePrefixes",
      },
      maxTextLength = {
         order = 30,
         name = L["Max text length"],
         desc = L["The maximum length of the text displayed in FuBar."],
         type = 'range',
         min = textLengthLowerBound,
         max = textLengthUpperBound,
         step = 1,
         get = "MaxTextLength",
         set = "SetMaxTextLength",
      },
      hideOutfitterMinimapIcon = {
         order = 40,
         name = L["Hide minimap button"],
         desc = L["Hide Outfitter's minimap button."],
         type = 'toggle',
         get = function() return not OutfitterMinimapButton:IsVisible() end,
         set = function(v) Outfitter_SetShowMinimapButton(not v) end,
      },
   }
}

function OutfitterFu:HideMissing()
   return self.db.profile.settings.hideMissing
end

function OutfitterFu:SetHideMissing(enabled)
   if enabled then
      self.db.profile.settings.hideMissing = true
   else
      self.db.profile.settings.hideMissing = false
   end
   self:UpdateTooltip()
end

function OutfitterFu:RemovePrefixes()
   return self.db.profile.settings.removePrefixes
end

function OutfitterFu:SetRemovePrefixes(enabled)
   if enabled then
      self.db.profile.settings.removePrefixes = true
   else
      self.db.profile.settings.removePrefixes = false
   end
   self:UpdateText()
end

function OutfitterFu:MaxTextLength()
   return self.db.profile.settings.maxTextLength
end

function OutfitterFu:SetMaxTextLength(length)
   if length > textLengthUpperBound then
      self.db.profile.settings.maxTextLength = textLengthUpperBound
      return
   end
   if length < textLengthLowerBound then
      self.db.profile.settings.maxTextLength = textLengthLowerBound
      return
   end
   self.db.profile.settings.maxTextLength = length
   self:UpdateText()
end

-- registers event callbacks with Outfitter and WoW
function OutfitterFu:OnEnable()
   -- TODO KTP detect these missing globals: Outfitter_RegisterOutfitEvent, Outfitter_IsInitialized,
   -- Outfitter_GetCurrentOutfitInfo, Outfitter_GetCategoryOrder, Outfitter_GetOutfitsByCategoryID,
   -- Outfitter_HasVisibleOutfits, Outfitter_OutfitIsVisible

   Outfitter_RegisterOutfitEvent('OUTFITTER_INIT', OutfitterFu_OutfitEvent)
   Outfitter_RegisterOutfitEvent('WEAR_OUTFIT', OutfitterFu_OutfitEvent)
   Outfitter_RegisterOutfitEvent('UNWEAR_OUTFIT', OutfitterFu_OutfitEvent)
   self:RegisterEvent('PLAYER_ENTERING_WORLD', 'Update')
   self:RegisterEvent('ZONE_CHANGED_NEW_AREA', 'Update')
   self:RegisterEvent('BANKFRAME_OPENED', 'Update')
   self:RegisterEvent('BANKFRAME_CLOSED', 'Update')
end

function OutfitterFu:SetBoundedText(colorCode, text)
   local t = text
   if self:RemovePrefixes() then
      local replacements = 0
	t, replacements = string.gsub(t,"^%a+:%s+", "")
   end
   local length = string.len(t)
   local maxLength = self:MaxTextLength()
   if length > maxLength then
		t = string.sub(t,1, maxLength - 3) .. '...'
   end
   self:SetText(colorCode .. t .. '|r')
end

-- updates text in FuBar
function OutfitterFu:OnTextUpdate()
   if not Outfitter_IsInitialized() then
      self:SetBoundedText(NORMAL_FONT_COLOR_CODE, L["Initializing"])
      return
   end
   
   local name, vOutfit = Outfitter_GetCurrentOutfitInfo()
   local vEquippableItems = OutfitterItemList_GetEquippableItems()
   local vMissingItems, vBankedItems = OutfitterItemList_GetMissingItems(vEquippableItems, vOutfit)

   local vItemColor = NORMAL_FONT_COLOR_CODE
   if vMissingItems then
      vItemColor = RED_FONT_COLOR_CODE
   elseif vBankedItems then
      vItemColor = BANKED_FONT_COLOR_CODE
   end
   
   self:SetBoundedText(vItemColor, name)
end

-- updates FuBar tooltip
function OutfitterFu:OnTooltipUpdate()
   if not Outfitter_IsInitialized() then
      Tablet:AddCategory():AddLine(
        'text', L["Initializing"]
      )
      return
   end
   
   -- Tablet:SetHint(L["Click to toggle Outfitter window"])

   local vEquippableItems = OutfitterItemList_GetEquippableItems()
   local category
   
   for vCategoryIndex, vCategoryID in ipairs(Outfitter_GetCategoryOrder()) do
      local vCategoryName = getglobal("Outfitter_c" .. vCategoryID .. "Outfits")
      local vOutfits = Outfitter_GetOutfitsByCategoryID(vCategoryID)
      
      if Outfitter_HasVisibleOutfits(vOutfits) then
         category = Tablet:AddCategory(
            'id', vCategoryID,
            'text', vCategoryName,
            'textR', 1,
            'textG', 1,
            'textB', 1,
            'hideBlankLine', true,
            'showWithoutChildren', true,
            'hasCheck', true,
            'checked', true,
            'checkIcon', self.db.profile.settings.hiddenCategories[vCategoryID] and 'Interface\\Buttons\\UI-PlusButton-Up' or 'Interface\\Buttons\\UI-MinusButton-Up',
            'func', 'ToggleCategory',
            'arg1', self,
            'arg2', vCategoryID,
            'child_func', 'OutfitClick',
            'child_arg1', self
         )
         
         if (not self.db.profile.settings.hiddenCategories[vCategoryID]) then
            for vIndex, vOutfit in pairs(vOutfits) do
               if Outfitter_OutfitIsVisible(vOutfit) then
                  local vMissingItems, vBankedItems = OutfitterItemList_GetMissingItems(vEquippableItems, vOutfit)

		  if not vMissingItems or not self:HideMissing() then
                     local vWearingOutfit = Outfitter_WearingOutfit(vOutfit)
                     local vItemColor = NORMAL_FONT_COLOR
                  
                     if vMissingItems then
                        vItemColor = RED_FONT_COLOR
                     elseif vBankedItems then
                        vItemColor = BANKED_FONT_COLOR
                     end
                  
                     category:AddLine(
                        'text', ' ' .. vOutfit.Name,
                        'textR', vItemColor.r,
                        'textG', vItemColor.g,
                        'textB', vItemColor.b,
                        'arg2', {CategoryID = vCategoryID, Index = vIndex},
                        'hasCheck', true,
                        'checked', vWearingOutfit,
                        'indentation', 12
                     )
		  end
               end
            end
         end
      end
   end
end

-- callback for tooltip menu category click
function OutfitterFu:ToggleCategory(id, button)
   if self.db.profile.settings.hiddenCategories[id] then
      self.db.profile.settings.hiddenCategories[id] = false
   else
      self.db.profile.settings.hiddenCategories[id] = true
   end
   self:UpdateTooltip()
end

-- callback for tooltip menu outfit click
function OutfitterFu:OutfitClick(outfitRef, button)
   OutfitterMinimapButton_ItemSelected(nil, outfitRef)
   self:Update()
end

-- toggles the Outfitter frame
function OutfitterFu:OnClick()
   if (CharacterFrame:IsVisible() and OutfitterFrame:IsVisible()) then
      HideUIPanel(CharacterFrame)
      OutfitterFrame:Hide()
   else
      ShowUIPanel(CharacterFrame)
      CharacterFrame_ShowSubFrame("PaperDollFrame")
      OutfitterFrame:Show()
   end
end
