--[[ Reagent Banker by Tuhljin 2020
local CHATLOG = false
AutoReagentDeposit = {}
local AutoReagentBank = CreateFrame("Frame")
AutoReagentDeposit.Frame = AutoReagentBank
AutoReagentBank:Hide()
local seenBank
local prevContents, awaitingChanges
local REAGENTBANK_ID = ReagentBankFrame:GetID()
local DepositButton = ReagentBankFrame.DespositButton -- Blizzard typo
local LIMIT_LINKS_PER_LINE = 10  --3 --15

local function chatprint(msg)
	DEFAULT_CHAT_FRAME:AddMessage(msg, 1, (170 / 255), (128 / 255)); --1, 0.6, 0.4
end
local function doesBagSort(id)
	-- See ContainerFrameFilterDropDown_Initialize in FrameXML\ContainerFrame.lua
	if (id == -1) then
		return not GetBankAutosortDisabled()
	elseif (id == 0) then
		return not GetBackpackAutosortDisabled()
	elseif (id > NUM_BAG_SLOTS) then
		return not GetBankBagSlotFlag(id - NUM_BAG_SLOTS, LE_BAG_FILTER_FLAG_IGNORE_CLEANUP)
	else
		return not GetBagSlotFlag(id, LE_BAG_FILTER_FLAG_IGNORE_CLEANUP)
	end
end
local function setBagSort(id, value)
	-- See ContainerFrameFilterDropDown_Initialize in FrameXML\ContainerFrame.lua
	if (id == -1) then
		SetBankAutosortDisabled(not value)
	elseif (id == 0) then
		SetBackpackAutosortDisabled(not value)
	elseif (id > NUM_BAG_SLOTS) then
		SetBankBagSlotFlag(id - NUM_BAG_SLOTS, LE_BAG_FILTER_FLAG_IGNORE_CLEANUP, not value)
	else
		SetBagSlotFlag(id, LE_BAG_FILTER_FLAG_IGNORE_CLEANUP, not value)
	end
end
local function makeBagsSort()
	local changed
	for id=0,NUM_BAG_SLOTS do
		if (not doesBagSort(id)) then
			setBagSort(id, true)
			if (not changed) then  changed = {};  end
			changed[#changed+1] = id
		end
	end
	return changed
end
local function getReagentBankContents()
	local tab = {}
	local _, count, itemID
	local GetContainerItemInfo = C_Container and _G.C_Container.GetContainerItemInfo or _G.GetContainerItemInfo
	for slot=1,ReagentBankFrame.size do
		--texture, count, locked, quality, readable, lootable, link, isFiltered, hasNoValue, itemID
		_, count, _, _, _, _, _, _, _, itemID = GetContainerItemInfo(REAGENTBANK_ID, slot)
		if (itemID) then
			--print("GetContainerItemInfo(",REAGENTBANK_ID,",", slot,") => ",count,itemID)
			tab[itemID] = (tab[itemID] or 0) + count
		end
	end
	return tab
end
AutoReagentDeposit.GetReagentBankContents = getReagentBankContents
local preDeposit, postDeposit
do
	local changedSortFlag
	function preDeposit(includeSortIgnored)
		local GetContainerItemInfo = C_Container and _G.C_Container.GetContainerItemInfo or _G.GetContainerItemInfo
		changedSortFlag = includeSortIgnored and makeBagsSort() or nil
		if (CHATLOG) then
			prevContents = getReagentBankContents()
			awaitingChanges = true
		else
			prevContents = nil
			awaitingChanges = false
		end
	end
	function postDeposit()
		if (changedSortFlag) then
			for i,id in ipairs(changedSortFlag) do
				setBagSort(id, false)
			end
			changedSortFlag = nil
		end
	end
end
local function depositReaction()
	local newContents = getReagentBankContents()
	local numAdded = 0 -- numAdded is the number of item IDs that saw an addition of any size
	local added = {}
	for id,count in pairs(newContents) do
		local prev = prevContents[id] or 0
		if (count > prev) then
			if (not added) then  added = {};  end
			added[id] = count - prev
			numAdded = numAdded + 1
		end
	end
	prevContents = nil

	if (numAdded > 0) then
		local numLines, numLeft = 0, numAdded
		local links = {}
		for id,diff in pairs(added) do
			local _, link = GetItemInfo(id)
			links[#links + 1] = diff == 1 and link or L.CHATLOG_DEPOSITED_COUNT:format(link, diff)
			numLeft = numLeft - 1
			if (#links == LIMIT_LINKS_PER_LINE) then
				local s = table.concat(links, L.CHATLOG_DEPOSITED_SEP .. ' ')
				if (numLeft > 0) then  s = s .. L.CHATLOG_DEPOSITED_SEP;  end
				links = {}
				numLines = numLines + 1
				chatprint(numLines == 1 and L.CHATLOG_DEPOSITED:format(s) or "   " .. s)
			end
		end
		if (#links > 0) then
			local s = table.concat(links, L.CHATLOG_DEPOSITED_SEP .. ' ')
			numLines = numLines + 1
			chatprint(numLines == 1 and L.CHATLOG_DEPOSITED:format(s) or "   " .. s)
		end
	end
end
local function OnEvent(self, event, ...)
	if (event == "BANKFRAME_OPENED") then
		if (not IsReagentBankUnlocked()) then end
		if (not seenBank) then
		 	ReagentBankFrame_OnShow(ReagentBankFrame)
			seenBank = true
		end
		C_Timer.After(0, function() -- This delay may prevent the intermittent problem where items already in the reagent bank appear to be newly deposited because getReagentBankContents() somehow failed to find any items when called by preDeposit().
			preDeposit()
			DepositReagentBank()
			postDeposit()
		end)
	elseif (event == "PLAYERREAGENTBANKSLOTS_CHANGED") then
		if (awaitingChanges) then
			awaitingChanges = false
			-- Consolidate all PLAYERREAGENTBANKSLOTS_CHANGED events into one reaction:
			C_Timer.After(0, depositReaction) -- 0 seconds because we should receive all the events at once so the function ought to be triggered after all of them are in
		end
	end
end
AutoReagentBank:RegisterEvent("ADDON_LOADED")
AutoReagentBank:SetScript("OnEvent", function(self, event, arg1)
  if R.db["Misc"]["AutoReagentInBank"] and (arg1 == "OrzUI") then
		AutoReagentBank:UnregisterEvent("ADDON_LOADED")
		AutoReagentBank:SetScript("OnEvent", OnEvent)
		AutoReagentBank:RegisterEvent("BANKFRAME_OPENED")
	end
end)
local DepositButton_click_old = DepositButton:GetScript("OnClick")
DepositButton:SetScript("OnClick", function(...)
	preDeposit()
	DepositButton_click_old(...)
	postDeposit()
end)]]

--[[----------------------------------------------------------------------------- ItemQualityIcons
hooksecurefunc("SetItemButtonQuality", function(button, quality, itemIDOrLink)
	button.IconBorder:Hide()

	local qualityIcon = button.qualityIcon
	if not qualityIcon then
		qualityIcon = CreateFrame("Frame", nil, button)
		qualityIcon:SetAllPoints()
		button.qualityIcon = qualityIcon
	end

	local iconColor = button.iconColor
	if not iconColor then
		iconColor = qualityIcon:CreateTexture("iconColor", "OVERLAY")
		iconColor:SetTexture("Interface\\AddOns\\OrzUI\\Media\\Modules\\Role\\bubbleTex")
		iconColor:ClearAllPoints()
		iconColor:SetPoint("TOPRIGHT", -5, -5)
		iconColor:SetSize(9, 9)
	end

	if quality then
		if BAG_ITEM_QUALITY_COLORS[quality] and quality ~= 1 then
			iconColor:SetVertexColor(BAG_ITEM_QUALITY_COLORS[quality].r, BAG_ITEM_QUALITY_COLORS[quality].g, BAG_ITEM_QUALITY_COLORS[quality].b)
		elseif quality == 1 then
			iconColor:SetVertexColor(1, 1, 1)
		elseif quality == 0 then
			iconColor:SetVertexColor(0.61568, 0.61568, 0.61568)
		end

		button.qualityIcon:Show()
	else
		button.qualityIcon:Hide()
	end
end)]]

------------------------------------------------------------------------------- NiceDamage
--Local NiceDamage = CreateFrame("Frame", "NiceDamage");
--function NiceDamage:ApplySystemDamageFonts() DAMAGE_TEXT_FONT = "Interface\\AddOns\\OrzUI\\Media\\Fonts\\RedCircl.ttf"; end
--NiceDamage:SetScript("OnEvent", function() if (event == "ADDON_LOADED") then NiceDamage:ApplySystemDamageFonts() end end);
--NiceDamage:RegisterEvent("ADDON_LOADED");
--NiceDamage:ApplySystemDamageFonts()


--[[---------------------------- ## Notes: Automatically destroys items in the pre-defined list    ## Author: Tim @ WoW Interface    ## Version: 1.0
local itemList = {
	--[2287] = true,		-- haunch of meat (tested in RFC)  肉排
}
local DESTROY = CreateFrame("Frame", "AutoItemDestroyer")
DESTROY:RegisterEvent("BAG_UPDATE")
DESTROY:RegisterEvent("BAG_UPDATE_DELAYED")
DESTROY:RegisterEvent("CHAT_MSG_LOOT")
DESTROY:SetScript("OnEvent", function(_, event, ...)
   for bags = 0, 4 do
      for slots = 1, C_Container.GetContainerNumSlots(bags) do
         local itemLink, linkID = GetContainerItemLink(bags, slots), C_Container.GetContainerItemID(bags, slots)
         if (itemLink and linkID) then
            if (select(11, GetItemInfo(itemLink)) ~= nil and select(2, GetContainerItemInfo(bags, slots)) ~= nil) then
               local itemName, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = GetItemInfo(linkID) 
               if itemList[linkID] then
                  PickupContainerItem(bags, slots)
                  DeleteCursorItem()
                  --print("Searched bags... FOUND & DESTROYED: |cff6699dd", itemName.." [ID: "..linkID.."]")
               end
            end
         end
      end
   end
end)]]

--## Author: Rubio ## Version: 11.1.0
local banner = false
local UntrackCompletedAchieves = CreateFrame("Frame")
UntrackCompletedAchieves:RegisterEvent("PLAYER_ENTERING_WORLD") 
UntrackCompletedAchieves:SetScript("OnEvent", function(self, event, ...)
	if event == "PLAYER_ENTERING_WORLD" then
    if not banner then banner = true end
    local tracked = C_ContentTracking.GetTrackedIDs(Enum.ContentTrackingType.Achievement) or {}
    for _, achievementID in ipairs(tracked) do
	local _, _, _, completed = GetAchievementInfo(achievementID)
	if completed then
	    C_ContentTracking.StopTracking(Enum.ContentTrackingType.Achievement, achievementID, Enum.ContentTrackingStopType.Collected)
	end
    end
	end
end)

-- ReloadUI Made by Sharpedge_Gaming ## Version: v.2.9
local function CreateGameMenuButton()
    local button = CreateFrame("Button", "GameMenuButtonReloadButton", GameMenuFrame, "GameMenuButtonTemplate")
    button:SetText(RELOADUI)
    button:SetSize(100, 28)
    button:SetScript("OnClick", function()
        PlaySound(SOUNDKIT.IG_MAINMENU_LOGOUT)
        ReloadUI()
    end)
    button:GetFontString():SetFont(STANDARD_TEXT_FONT, 15)
    GameMenuFrame:HookScript("OnShow", function()
        button:SetPoint("TOP", GameMenuFrame, "TOP", 0, -23) 
    end)
end

local function CreateSettingsPanelButton()
    local button = CreateFrame("Button", "SettingsPanelReloadUI", SettingsPanel, "UIPanelButtonTemplate")
    button:SetText(RELOADUI)
    button:SetSize(96, 22)
    button:SetPoint("BOTTOMLEFT", SettingsPanel, "BOTTOMLEFT", 16, 16)
    button:SetScript("OnClick", function()
        PlaySound(SOUNDKIT.IG_MAINMENU_LOGOUT)
        ReloadUI()
        HideUIPanel(InterfaceOptionsFrame)
    end)
end

local function InitializeButtons()
    CreateGameMenuButton()
    CreateSettingsPanelButton()
end

local eventFrame = CreateFrame("Frame")
eventFrame:RegisterEvent("ADDON_LOADED")
eventFrame:SetScript("OnEvent", function(self, event, arg1)
    if event == "ADDON_LOADED" and arg1 == "OrzUI" then
        C_Timer.After(0.1, InitializeButtons)
        self:UnregisterEvent("ADDON_LOADED")
    end
end)


----------------------------------------------------------------------------------------
-- Learn all available skills(TrainAll by SDPhantom)
----------------------------------------------------------------------------------------
local frame = CreateFrame("Frame")
frame:RegisterEvent("ADDON_LOADED")
frame:SetScript("OnEvent", function(_, _, addon)
	if addon == "Blizzard_TrainerUI" then
		local cost, num
		local button = CreateFrame("Button", "ClassTrainerTrainAllButton", ClassTrainerFrame, "UIPanelButtonTemplate")
		button:SetText(ACHIEVEMENTFRAME_FILTER_ALL)
		button:SetScript("OnEnter", function()
			GameTooltip:SetOwner(button, "ANCHOR_RIGHT")
			GameTooltip:SetText(AVAILABLE..": "..num.."\n"..COSTS_LABEL.." "..GetMoneyString(cost))
		end)
		button:SetScript("OnLeave", function()
			GameTooltip:Hide()
		end)
		button:SetPoint("TOPRIGHT", ClassTrainerTrainButton, "TOPLEFT", 0, 0)
		button:SetWidth(min(50, button:GetTextWidth() + 15))
		button:SetScript("OnClick", function()
			for i = 1, GetNumTrainerServices() do
				if select(2, GetTrainerServiceInfo(i)) == "available" then
					BuyTrainerService(i)
				end
			end
		end)
		hooksecurefunc("ClassTrainerFrame_Update", function()
			num, cost = 0, 0
			for i = 1, GetNumTrainerServices() do
				if select(2, GetTrainerServiceInfo(i)) == "available" then
					num = num + 1
					cost = cost + GetTrainerServiceCost(i)
				end
			end
			button:SetEnabled(num > 0)
		end)
	end
end)

----------------------------------------------------------------------------------------
--	Sum up all current auctions(Sigma by Ailae)
----------------------------------------------------------------------------------------
local frame = CreateFrame("Frame")
frame:RegisterEvent("ADDON_LOADED")
frame:SetScript("OnEvent", function(_, _, addon)
	if addon == "Blizzard_AuctionHouseUI" then
		local f = CreateFrame("Frame", nil, AuctionHouseFrame)
		f:SetSize(200, 20)
		f:SetPoint("LEFT", AuctionHouseFrame.MoneyFrameBorder, "RIGHT", 38, -1)

		local text = f:CreateFontString(nil, "OVERLAY", "PriceFont")
		text:SetPoint("LEFT")

		f:RegisterEvent("OWNED_AUCTIONS_UPDATED")
		f:SetScript("OnEvent", function()
			local totalBuyout = 0
			local totalBid = 0

			for i = 1, C_AuctionHouse.GetNumOwnedAuctions() do
				local info = C_AuctionHouse.GetOwnedAuctionInfo(i)
				if info.buyoutAmount then
					totalBuyout = totalBuyout + (info.buyoutAmount * info.quantity)
				end
				if info.bidAmount then
					totalBid = totalBid + info.bidAmount
				end
			end

			if totalBid > 0 and totalBuyout > 0 then
				text:SetText(BIDS..": "..C_CurrencyInfo.GetCoinTextureString(totalBid).."     "..BUYOUT..": "..C_CurrencyInfo.GetCoinTextureString(totalBuyout))
			elseif totalBid > 0 and totalBuyout == 0 then
				text:SetText(BIDS..": "..C_CurrencyInfo.GetCoinTextureString(totalBid))
			elseif totalBid == 0 and totalBuyout > 0 then
				text:SetText(BUYOUT..": "..C_CurrencyInfo.GetCoinTextureString(totalBuyout))
			else
				text:SetText("")
			end
		end)
	end
end)

----------------------------------------------------------------------------------------
--	Alt+Click to buy a stack
----------------------------------------------------------------------------------------
hooksecurefunc("MerchantItemButton_OnModifiedClick", function(self)
	if IsAltKeyDown() then
		local id = self:GetID()
		local itemLink = GetMerchantItemLink(id)
		if not itemLink then return end

		local maxStack = select(8, C_Item.GetItemInfo(itemLink))
		if maxStack and maxStack > 1 then
			local numAvailable = select(5, GetMerchantItemInfo(id))
			if numAvailable > -1 then
				BuyMerchantItem(id, numAvailable)
			else
				BuyMerchantItem(id, GetMerchantItemMaxStack(id))
			end
		end
	end
end)

ITEM_VENDOR_STACK_BUY = _G.ITEM_VENDOR_STACK_BUY.."\n|cff00ff00<".."Alt+右键购买一组"..">|r"

----------------------------------------------------------------------------------------
--	Show item level for weapons and armor in merchant
----------------------------------------------------------------------------------------
hooksecurefunc("MerchantFrame_UpdateMerchantInfo", function()
	local numItems = GetMerchantNumItems()

	for i = 1, MERCHANT_ITEMS_PER_PAGE do
		local index = (MerchantFrame.page - 1) * MERCHANT_ITEMS_PER_PAGE + i
		if index > numItems then return end

		local button = _G["MerchantItem"..i.."ItemButton"]
		if button and button:IsShown() then
			if not button.text then
				button.text = button:CreateFontString(nil, "OVERLAY", "SystemFont_Outline_Small")
				button.text:SetPoint("TOPLEFT", 1, -1)
				button.text:SetTextColor(1, 1, 0)
			else
				button.text:SetText("")
			end

			local itemLink = GetMerchantItemLink(index)
			if itemLink then
				local _, _, quality, itemlevel, _, _, _, _, _, _, _, itemClassID = C_Item.GetItemInfo(itemLink)
				if (itemlevel and itemlevel > 1) and (quality and quality > 1) and (itemClassID == Enum.ItemClass.Weapon or itemClassID == Enum.ItemClass.Armor) then
					button.text:SetText(itemlevel)
				end
			end
		end
	end
end)

----------------------------------------------------------------------------------------
--	Auto cancel various buffs(by Unknown)
----------------------------------------------------------------------------------------
local function SpellName(id)
	local name = C_Spell.GetSpellInfo(id)
	if name then
		return name
	else
		print("|cffff0000BadBuffs spell ID ["..tostring(id).."] no longer exists!|r")
		return "Empty"
	end
end

local BadBuffs = {
	[SpellName(58493)] = true,	-- Mohawked!
	[SpellName(44212)] = true,	-- Jack-o'-Lanterned!
	[SpellName(61716)] = true,	-- Rabbit Costume
	[SpellName(172010)] = true,	-- Abomination Costume
	[SpellName(24732)] = true,	-- Bat Costume
	[SpellName(172015)] = true,	-- Geist Costume
	[SpellName(24735)] = true,	-- Ghost Costume
	[SpellName(172008)] = true,	-- Ghoul Costume
	[SpellName(24712)] = true,	-- Leper Gnome Costume
	[SpellName(24710)] = true,	-- Ninja Costume
	[SpellName(24709)] = true,	-- Pirate Costume
	[SpellName(24723)] = true,	-- Skeleton Costume
	[SpellName(172003)] = true,	-- Slime Costume
	[SpellName(172020)] = true,	-- Spider Costume
	[SpellName(24740)] = true,	-- Wisp Costume
	[SpellName(61781)] = true,	-- Turkey Feathers
	[SpellName(61734)] = true,	-- Noblegarden Bunny
}

local UnitBuff = function(unit, auraIndex, filter)
	return AuraUtil.UnpackAuraData(C_UnitAuras.GetBuffDataByIndex(unit, auraIndex, filter))
end

local frame = CreateFrame("Frame")
frame:RegisterEvent("UNIT_AURA")
frame:SetScript("OnEvent", function(_, event, unit)
	if event == "UNIT_AURA" and unit == "player" and not InCombatLockdown() then
		local i = 1
		while true do
			local name = UnitBuff(unit, i)
			if not name then return end
			if BadBuffs[name] then
				CancelSpellByName(name)
				print("|cffffff00"..ACTION_SPELL_AURA_REMOVED.." ["..name.."].|r")
			end
			i = i + 1
		end
	end
end)