local LDB

local menu = {}
local startChar = {
	["AB"] = {
	},
	["CD"] = {
	},
	["EF"] = {
	},
	["GH"] = {
	},
	["IJ"] = {
	},
	["KL"] = {
	},
	["MN"] = {
	},
	["OP"] = {
	},
	["QR"] = {
	},
	["ST"] = {
	},
	["UV"] = {
	},
	["WX"] = {
	},
	["YZ"] = {
	}
}


local parent = CreateFrame('Frame')
local function pairsByKeys (startChar, f)
	local a = {}
		for n in pairs(startChar) do table.insert(a, n) end
		table.sort(a, f)
		local i = 0      -- iterator variable
		local iter = function ()   -- iterator function
			i = i + 1
			if a[i] == nil then return nil
			else return a[i], startChar[a[i]]
			end
		end
	return iter
end


local function UpdateDisplay()	
	if lastpetId ~= nil then
		LDB.text = lastpetText
		LDB.icon = lastpetIcon
	end
	
	local summonedPetID = C_PetJournal.GetSummonedPetID();
		
	if summonedPetID then
		local speciesID, customName, petlevel, xp, maxXp, displayID, petName, petIcon, petType, creatureID = C_PetJournal.GetPetInfoByPetID(summonedPetID)
		local creatureName = petName
			if customName then
				creatureName = customName
			end
			if creatureName then
			LDB.text = format("|cff00ff00%s|r", creatureName)
			LDB.icon = petIcon
			lastpetText = creatureName
			lastpetId = summonedPetID
			lastpetIcon = petIcon
			return
			end
	end
	
end

local function ModifiedClick(button, Id)
local speciesID, customName, petlevel, xp, maxXp, displayID, petName, petIcon, petType, creatureID = C_PetJournal.GetPetInfoByPetID(Id)
	local creatureName = petName
		if customName then
			creatureName = customName
		end
	
	if IsShiftKeyDown() then
		C_PetJournal.PickupPet(Id);
	elseif IsAltKeyDown() and not IsControlKeyDown() then
		fav1id = Id
		DEFAULT_CHAT_FRAME:AddMessage(string.format("|cffffff00BrokerPets:|r %s added as favorite 1.", creatureName))
	elseif IsControlKeyDown() and not IsAltKeyDown() then
		fav2id = Id
		DEFAULT_CHAT_FRAME:AddMessage(string.format("|cffffff00BrokerPets:|r %s added as favorite 2.", creatureName))
	elseif IsControlKeyDown() and IsAltKeyDown() then
		fav3id = Id
		DEFAULT_CHAT_FRAME:AddMessage(string.format("|cffffff00BrokerPets:|r %s added as favorite 3.", creatureName))
	else
		C_PetJournal.SummonPetByID(Id);
	end
end

local function OnTooltipShow(self)
	local numPets, numOwned = C_PetJournal.GetNumPets(false);
	self:AddLine('|cff00ffffBrokerPets|r')
	self:AddLine("<Right Click> to open pet list")
	self:AddLine("<Left Click> to summon/dismiss pet")
	self:AddLine("<Shift-Left Click> plugin to open pet journal")
	self:AddLine("<Shift-Right Click> plugin to open filter menu")
	self:AddLine("<Shift-Left Click> pet to pick it up")
	self:AddLine("<ALT-Click> pet to set as favorite 1")
	self:AddLine("<CTRL-Click> pet to set as favorite 2")
	self:AddLine("<CTRL-ALT-Click> pet to set as favorite 3")
	if numOwned == 0 then
	self:AddLine("|cffff0000You have no pets|r")
	else
	self:AddLine(string.format("|cff00ff00You have %s pets|r", numOwned))
	end
end

local function OnClick(self, button)
	if (button == 'RightButton' and not IsShiftKeyDown()) then
		ToggleDropDownMenu(1, nil, parent, self, 0, 0)
		--local numPets, numOwned = C_PetJournal.GetNumPets(false)
		--DEFAULT_CHAT_FRAME:AddMessage(string.format("|cffffff00BrokerPets:|r menu toggled %s", numPets))
	end
	if (IsShiftKeyDown() and button == 'LeftButton') then	
		TogglePetJournal()
		PetJournalParent_SetTab(PetJournalParent, 2)
		--SummonRandomCritter()
	end
	if (button == 'LeftButton' and not IsShiftKeyDown()) then	
		if lastpetId ~= nil then
			C_PetJournal.SummonPetByID(lastpetId);
		end
	end	
	if (IsShiftKeyDown() and button == 'RightButton') then
		if IsAddOnLoaded("Blizzard_PetJournal") then
			ToggleDropDownMenu(1, nil, PetJournalFilterDropDown, self, 0, 0)
		else
			local loaded, reason = LoadAddOn("Blizzard_PetJournal")
			ToggleDropDownMenu(1, nil, PetJournalFilterDropDown, self, 0, 0)
		end
	end
end

local function CreateMenu(self, level)
	menu = wipe(menu)
	local numPets, numOwned = C_PetJournal.GetNumPets(false)
	
	local firstChar
	if 	numPets <= 20 then
	for i = 1, numPets do
		--local speciesID, customName, level, xp, maxXp, displayID, petName, petIcon, petType, creatureID = C_PetJournal.GetPetInfoByPetID(id)
		local petID, speciesID, isOwned, customName, petlevel, favorite, isRevoked, name, icon, petType, creatureID, sourceText, description, isWildPet = C_PetJournal.GetPetInfoByIndex(i)
			local creatureName = name
			if customName then
				creatureName = customName
			end
		local isSummonable = C_PetJournal.PetIsSummonable(petID)
		--firstChar = strupper(strsub(creatureName, 1, 1))
		if isOwned then
		menu.hasArrow = false; -- Start menu creation
		menu.notCheckable = true;
		menu.text = creatureName
		menu.icon = icon
		menu.colorCode = "|cffffffff"
		menu.func = ModifiedClick
		menu.arg1 = petID
		
		if not isSummonable then
			menu.colorCode = "|cff848484"
		end
		
		local summonedPetID = C_PetJournal.GetSummonedPetID();
		if summonedPetID == petID then
			menu.colorCode = "|cff00ff00"
		end
			UIDropDownMenu_AddButton(menu)
		end
	end
	else
	level = level or 1
	
	if (level == 1) then
	for key, v in pairsByKeys(startChar) do
		menu.text = key
		menu.notCheckable = 1
		menu.hasArrow = true;
		menu.value = {
			["Level1_Key"] = key;
		};
	
		UIDropDownMenu_AddButton(menu, level)
	end
		if fav1id ~= nil then
			local speciesID, customName, petlevel, xp, maxXp, displayID, petName, petIcon, petType, creatureID = C_PetJournal.GetPetInfoByPetID(fav1id)
			local creatureName = petName
			if customName then
				creatureName = customName
			end
		local isSummonable = C_PetJournal.PetIsSummonable(fav1id)	
			menu.text = format ("1. %s", creatureName)
			menu.icon = petIcon
			menu.colorCode = "|cffffffff"
			menu.func = ModifiedClick
			menu.arg1 = fav1id
			menu.hasArrow = nil;
			menu.notCheckable = 1
			if not isSummonable then
				menu.colorCode = "|cff848484"
			end
			
			local summonedPetID = C_PetJournal.GetSummonedPetID();
			if summonedPetID == fav1id then
				menu.colorCode = "|cff00ff00"
			end
			UIDropDownMenu_AddButton(menu, level)
		end
		if fav2id ~= nil then
		local speciesID, customName, petlevel, xp, maxXp, displayID, petName, petIcon, petType, creatureID = C_PetJournal.GetPetInfoByPetID(fav2id)
			local creatureName = petName
			if customName then
				creatureName = customName
			end
		local isSummonable = C_PetJournal.PetIsSummonable(fav2id)	
			menu.text = format("2. %s", creatureName)
			menu.icon = petIcon
			menu.colorCode = "|cffffffff"
			menu.func = ModifiedClick
			menu.arg1 = fav2id
			menu.hasArrow = nil;
			menu.notCheckable = 1
			if not isSummonable then
				menu.colorCode = "|cff848484"
			end
			
			local summonedPetID = C_PetJournal.GetSummonedPetID();
			if summonedPetID == fav2id then
				menu.colorCode = "|cff00ff00"
			end
			UIDropDownMenu_AddButton(menu, level)
		end
		if fav3id ~= nil then
		local speciesID, customName, petlevel, xp, maxXp, displayID, petName, petIcon, petType, creatureID = C_PetJournal.GetPetInfoByPetID(fav3id)
			local creatureName = petName
			if customName then
				creatureName = customName
			end
		local isSummonable = C_PetJournal.PetIsSummonable(fav3id)	
			menu.text = format("3. %s", creatureName)
			menu.icon = petIcon
			menu.colorCode = "|cffffffff"
			menu.func = ModifiedClick
			menu.arg1 = fav3id
			menu.hasArrow = nil;
			menu.notCheckable = 1
			if not isSummonable then
				menu.colorCode = "|cff848484"
			end
			
			local summonedPetID = C_PetJournal.GetSummonedPetID();
			if summonedPetID == fav3id then
				menu.colorCode = "|cff00ff00"
			end
			UIDropDownMenu_AddButton(menu, level)
		end
	
	elseif (level == 2) then
	 -- getting values of first menu
    local Level1_Key = UIDROPDOWNMENU_MENU_VALUE["Level1_Key"];
		
    for i = 1, numPets do
		--local speciesID, customName, level, xp, maxXp, displayID, petName, petIcon, petType, creatureID = C_PetJournal.GetPetInfoByPetID(id)
		local petID, speciesID, isOwned, customName, petlevel, favorite, isRevoked, name, icon, petType, creatureID, sourceText, description, isWildPet = C_PetJournal.GetPetInfoByIndex(i)
			local creatureName = name
			if customName then
				creatureName = customName
			end
		local isSummonable = C_PetJournal.PetIsSummonable(petID)
		firstChar = strupper(strsub(creatureName, 1, 1))
		if isOwned then
		menu.hasArrow = false; -- Start menu creation
		menu.notCheckable = true;
		menu.text = creatureName
		menu.icon = icon
		menu.colorCode = "|cffffffff"
		menu.func = ModifiedClick
		menu.arg1 = petID
		
		if not isSummonable then
			menu.colorCode = "|cff848484"
		end
		
		local summonedPetID = C_PetJournal.GetSummonedPetID();
		if summonedPetID == petID then
			menu.colorCode = "|cff00ff00"
		end
		
		
		if firstChar >= "A" and firstChar <= "B" and Level1_Key == "AB" then
			UIDropDownMenu_AddButton(menu, level)
		end
		
		if firstChar >= "C" and firstChar <= "D" and Level1_Key == "CD" then
			UIDropDownMenu_AddButton(menu, level)
		end
		
		if firstChar >= "E" and firstChar <= "F" and Level1_Key == "EF" then
			UIDropDownMenu_AddButton(menu, level)
		end
		
		if firstChar >= "G" and firstChar <= "H" and Level1_Key == "GH" then
			UIDropDownMenu_AddButton(menu, level)
		end
		
		if firstChar >= "I" and firstChar <= "J" and Level1_Key == "IJ" then
			UIDropDownMenu_AddButton(menu, level)
		end
	
		if firstChar >= "K" and firstChar <= "L" and Level1_Key == "KL" then
			UIDropDownMenu_AddButton(menu, level)
		end
		
		if firstChar >= "M" and firstChar <= "N" and Level1_Key == "MN" then
			UIDropDownMenu_AddButton(menu, level)
		end
		
		if firstChar >= "O" and firstChar <= "P" and Level1_Key == "OP" then
			UIDropDownMenu_AddButton(menu, level)
		end
	
		if firstChar >= "Q" and firstChar <= "R" and Level1_Key == "QR" then
			UIDropDownMenu_AddButton(menu, level)
		end
		
		if firstChar >= "S" and firstChar <= "T" and Level1_Key == "ST" then
			UIDropDownMenu_AddButton(menu, level)
		end
		
		if firstChar >= "U" and firstChar <= "V" and Level1_Key == "UV" then
			UIDropDownMenu_AddButton(menu, level)
		end
		
		if firstChar >= "W" and firstChar <= "X" and Level1_Key == "WX" then
			UIDropDownMenu_AddButton(menu, level)
		end
		
		if firstChar >= "Y" and firstChar <= "Z" and Level1_Key == "YZ" then
			UIDropDownMenu_AddButton(menu, level)
		end
	end
	end
	end
end
end


function parent:PLAYER_LOGIN()
	LDB = LibStub('LibDataBroker-1.1'):NewDataObject('BrokerPets', {
		icon = "Interface\\Icons\\INV_Misc_QuestionMark.blp",
		text = "BrokerPets",
		type = 'data source',
		OnTooltipShow = OnTooltipShow,
		OnClick = OnClick,
	})

	self:RegisterEvent('COMPANION_UPDATE')
	self.COMPANION_UPDATE = UpdateDisplay
	
	self:RegisterEvent("PET_JOURNAL_LIST_UPDATE")
	self.PET_JOURNAL_LIST_UPDATE = UpdateDisplay
	
	self.initialize = CreateMenu
	self.displayMode = 'MENU'

	UpdateDisplay()
end

parent:SetScript('OnEvent', function(self, event, ...) self[event](self, ...) end)
parent:RegisterEvent('PLAYER_LOGIN')