Quantcast
local addon = select(2, ...)
local module = addon:CreateModule"Lookup"

local POPUP_BUTTON = "BATTLE_PET_LOOKUP"
local POPUP_BUTTON_TEXT = "Pet Journal Lookup"

local function PetJournal_ScrollTo(self, index)
	local scroll = self.listScroll
	local bar = scroll.scrollBar

	local height = scroll.buttonHeight
	local val = (index - 1) * height

	bar:SetValue(val)
end

function module:ShowUnit(unit)
	local guid = UnitGUID(unit)

	if not guid then return end

	local index, species = addon:GetPetInfoByGUID(guid)

	if species then
		if not PetJournalParent or not PetJournalParent:IsShown() then
			TogglePetJournal(2)
		end

		addon:ClearPetJournalFilters(true)

		-- Selecting and scrolling can't be done in the same function
		-- call as clearing the filters since there needs to be events
		-- fired inbetween.
		self:DelayedCall(0.1, function()
			PetJournal_SelectSpecies(PetJournal, species)
			PetJournal_ScrollTo(PetJournal, index)
		end)
	end
end

local function SwapButtons(a, b)
	local p, r, rp, x, y = a:GetPoint(0)

	a:ClearAllPoints()
	a:SetPoint(b:GetPoint(0))


	b:ClearAllPoints()
	b:SetPoint(p, r, rp, x, y)
end


--[[ This Unit Popup stuff is seriously hacky. Doing it the Blizzard way makes
     the "Set Focus" option get blocked because of taint. Instead we add a button
     ourselves to the dropdown and then swap it with the cancel button to make appear
     in the right position.

     I hope this doesn't make things blow up, at least it doesn't block "Set Focus". --]]
local function UnitPopup_ShowMenu_hook(dropdown, which, unit, name, userdata)
	if not unit then return end
	if not (UnitIsWildBattlePet(unit) or UnitIsBattlePetCompanion(unit)) then return end
	if UIDROPDOWNMENU_MENU_LEVEL ~= 1 then return end

	local info = UIDropDownMenu_CreateInfo()
	info.text = POPUP_BUTTON_TEXT
	info.value = POPUP_BUTTON
	info.isNotRadio = true
	info.notCheckable = true
	info.func = function(...) module:ShowUnit(unit) end

	UIDropDownMenu_AddButton(info, 1)

	local cancelbutt, lookupbutt
	local dropdownlist = DropDownList1
	local numbutt = dropdownlist.numButtons

	for i = 1, numbutt do
		local button = _G["DropDownList1Button"..i]
		if button then
			if button then
				if button.value == "CANCEL" then
					cancelbutt = button
				end

				if button.value == POPUP_BUTTON then
					lookupbutt = button
				end
			end
		end
	end

	if cancelbutt and lookupbutt then
		SwapButtons(cancelbutt, lookupbutt)
	end
end

function module:Enable()
	hooksecurefunc("UnitPopup_ShowMenu", UnitPopup_ShowMenu_hook)
end

local function OnUpdate(self, e)
	self.elapsed = self.elapsed + e

	if self.elapsed >= self.delayedtime then
		self.delayedfunc()
		self:SetScript("OnUpdate", nil)
	end
end

function module:DelayedCall(time, func)
	self.delayedfunc = func
	self.delayedtime = time
	self.elapsed = 0
	self:SetScript("OnUpdate", OnUpdate)
end