local LOCKED = LOCKED -- "Locked"
local LOCKPICKING = GetSpellInfo(1804) -- "Pick Lock"
local LOCKPICKTIP = "|cffffff00<右键点击开锁>"
ProspectOreHerbsTable = {}

local sides = {"Left", "Right"}

local ignores = {}

local function isDoAble()
	local proftype, itemName, tipLine, itemLink
	itemName, itemLink = GameTooltip:GetItem()
	tipLine = LOCKPICKTIP
	for i = 1, GameTooltip:NumLines() do
		for _, side in pairs(sides) do
			local tt = _G["GameTooltipText" .. side .. i]:GetText()
			if tt == LOCKED then
				proftype = LOCKPICKING
				-- tipLine = tipLine .. "Unlock " .. itemName .. ".|r"
				return proftype, tipLine
			end
		end
	end
	return nil, nil
end

local buttons = {}

local function hookParent(f)
	f:HookScript("OnHide", function(self)
		for _, v in ipairs(buttons) do
			v:Hide()
		end
	end)
	function hookParent(f) end
end

local function GetMacroText(self)
	local mod = self.proftype == "[mod:shift] " or ""
	return "/cast " .. mod .. self.proftype .. "\n/use " .. self.bag .. " " .. self.slot
end             

local i = 1
local proftype, tipLine

local function CreateItemButtonOverlay(itemFrame)
	local bag = itemFrame:GetParent():GetID()
	local slot = itemFrame:GetID()
	local parent = itemFrame:GetParent()
	local fname = itemFrame:GetName()
	if fname then
		fname = fname .. "Overlay"
	else
		fname = "ProspectOverlay" .. i
		i = i + 1
	end
	local button = CreateFrame("Button", fname, parent, "ItemButtonTemplate,SecureActionButtonTemplate")
	table.insert(buttons, button)
	hookParent(parent)
	button:SetID(slot)
	button.slot = slot
	button.bag = bag
	button:SetAttribute("*type2", "macro")
	button:SetAttribute("*type*", "click")
	button:SetAttribute("*clickbutton1", itemFrame)
	button:SetAttribute("clickbutton2", ATTRIBUTE_NOOP)
	button:RegisterForClicks("AnyUp")
	button:RegisterForDrag("LeftButton")	
	button:SetFrameStrata("DIALOG")
	button:SetScript("OnShow", function(self)
		proftype, tipLine = isDoAble()
		self.proftype = proftype
		self:SetAttribute("*macrotext2", GetMacroText(self))
	end)
	button:SetScript("OnLeave", function(self, ...)
		tipLine = nil
		self:Hide()
		itemFrame:GetScript("OnLeave")(itemFrame, ...)		   
	end)
	button:SetScript("OnReceiveDrag", function(self, ...)
		self:Hide()
		itemFrame:GetScript("OnReceiveDrag")(itemFrame, ...)
	end)
	button:SetScript("OnDragStart", function(self, ...)
		self:Hide()
		itemFrame:GetScript("OnDragStart")(itemFrame, ...)
	end)
	button:SetScript("OnEnter", function(self, ...) 
		itemFrame:GetScript("OnEnter")(itemFrame, ...) 
	end)
	button.UpdateTooltip = function(self, ...) 
		itemFrame:UpdateTooltip(...)
	end
	return button
end
-- just a little experiment
local itemID, itemLink, checkOre
--[[ I really don't need this at all.
local function GetSpellId(spellName)
	for i = 1, 51005 do
		if GetSpellInfo(i) == spellName then
			return i
		end
	end
end
--]]
GameTooltip:HookScript("OnTooltipSetItem", function(self, ...)
	if tipLine then
		GameTooltip:AddLine(tipLine)
	end
end)
local worker = function(self)
	if GameTooltip:IsShown() and not InCombatLockdown() and not (ignores["BANKFRAME"] or ignores["GUILDBANKFRAME"] or ignores["MAIL"] or ignores["MERCHANT"] or ignores["TRADE"] or ignores["AUCTION_HOUSE"]) then
		proftype, tipLine = isDoAble()
		if proftype then
			local itemID = strmatch((select(2, GameTooltip:GetItem()) or ""), "item:(%d*):")
			if itemID and checkOre and not ProspectOreHerbsTable[itemID] then
				ProspectOreHerbsTable[itemID] = {}
			end
			local r, g, b = ChatTypeInfo["SYSTEM"]
			if ProspectOreHerbsTable[itemID] then
				for itemName, data in pairs(ProspectOreHerbsTable[itemID]) do
					local looted, multipleDiff, multipleDiffText, countPerLoot, chancePerLoot = (ProspectOreHerbsTable[itemID]["looted"] or 0), 0, ""
					if itemName ~= "looted" then
						countPerLoot = floor(data["total"] / data["count"])
						chancePerLoot = floor(data["total"] / looted * 100)
						if chancePerLoot > 100 then
							multipleDiff = min(chancePerLoot - 100, 100)
							chancePerLoot = 100
						end
						if multipleDiff > 0 then
							multipleDiffText = "(" .. multipleDiff .. "% chance for milti-drop)"
						end
						GameTooltip:AddDoubleLine(itemName, countPerLoot .. "/loot " .. chancePerLoot .. "% chance " .. multipleDiffText, r, g, b, r, g, b)
					end
				end
			end
			GameTooltip:Show()
			local button = self.ProspectButton 
			if not button then
				button = CreateItemButtonOverlay(self)
				self.ProspectButton = button
			end
			button:ClearAllPoints()
			local scale = self:GetEffectiveScale()
--			button:SetWidth(self:GetWidth() * scale)
--			button:SetHeight(self:GetHeight() * scale)
			button:SetParent(self)
			button:SetAllPoints(--[[self:GetPoint(1)]])
			button.proftype = proftype
			button:SetAttribute("*macrotext2", GetMacroText(button))
			button:Show()
		end
	end
end

local f = CreateFrame("Frame")
f:SetScript("OnEvent", function(self, event, ...)
	local frame1, frame2, opened = strsplit("_", event)
	if not opened then
		opened = frame2
		frame2 = nil
	end
	if frame2 then
		frame1 = frame1 .. "_" .. frame2
	end
	if opened == "OPENED" or opened == "SHOW" then
		ignores[frame1] = 1
	elseif opened == "CLOSED" then
		ignores[frame1] = nil
	end
	if event == "PLAYER_ENTERING_WORLD" then
		if IsAddOnLoaded("TBag") then
			local tbagOnEnter = TBag.ItemButton.OnEnter
			local tbagOnLeave = TBag.ItemButton.OnLeave
			function TBag.ItemButton.OnEnter(self, motion)
				if not self.Prospect_Called then
					tbagOnEnter(self, motion)
					self.Prospect_Called = 1
				end
				worker(self)
			end
 	  		function TBag.ItemButton.OnLeave(self, motion)
 	  			self.Prospect_Called = nil
				tbagOnLeave(self, motion)
 	  		end
		end
		self:UnregisterEvent("PLAYER_ENTERING_WORLD")
	end
end)

f:RegisterEvent("BANKFRAME_OPENED")
f:RegisterEvent("BANKFRAME_CLOSED")
-- f:RegisterEvent("GUILDBANKFRAME_OPENED")
-- f:RegisterEvent("GUILDBANKFRAME_CLOSED")
f:RegisterEvent("MAIL_SHOW")
f:RegisterEvent("MAIL_CLOSED")
f:RegisterEvent("MERCHANT_SHOW")
f:RegisterEvent("MERCHANT_CLOSED")
f:RegisterEvent("TRADE_SHOW")
f:RegisterEvent("TRADE_CLOSED")
f:RegisterEvent("AUCTION_HOUSE_SHOW")
f:RegisterEvent("AUCTION_HOUSE_CLOSED")
f:RegisterEvent("PLAYER_ENTERING_WORLD")

hooksecurefunc("ContainerFrameItemButton_OnEnter", worker)

local f = CreateFrame("Frame")

f:RegisterEvent("LOOT_OPENED")
f:RegisterEvent("LOOT_CLOSED")
f:SetScript("OnEvent", function(self, event)
	if event == "LOOT_OPENED" then
		if ProspectOreHerbsTable[itemID] then
			ProspectOreHerbsTable[itemID]["looted"] = (ProspectOreHerbsTable[itemID]["looted"] or 0) + 1
			for i = 1, GetNumLootItems() do
				local itemName, lootQuantity = select(2, GetLootSlotInfo(i))
				if not ProspectOreHerbsTable[itemID][itemName] then
					ProspectOreHerbsTable[itemID][itemName] = {}
				end
				ProspectOreHerbsTable[itemID][itemName]["total"] = (ProspectOreHerbsTable[itemID][itemName]["total"] or 0) + lootQuantity
				ProspectOreHerbsTable[itemID][itemName]["count"] = (ProspectOreHerbsTable[itemID][itemName]["count"] or 0) + 1
			end
		end
	elseif event == "LOOT_CLOSED" then
		itemID, itemLink, checkOre = nil, nil, nil
	end
end)

--[[ So I don't have to keep scrolling up for copy 'n paste
local PROSPECT_ID = 31252
local MILLING_ID = 51005
local DE_ID = 13262
local PROSPECT = GetSpellInfo(PROSPECT_ID) -- "Prospecting"
local PROSPECTABLE = ITEM_PROSPECTABLE -- "Prospectable"
local MILLING = GetSpellInfo(MILLING_ID) -- "Milling"
local MILLABLE = ITEM_MILLABLE -- "Millable"
local LOCKED = LOCKED -- "Locked"
local LOCKPICKING = GetSpellInfo(1804) -- "Pick Lock"
local DE = GetSpellInfo(DE_ID) -- "Disenchant"
--]]

hooksecurefunc("UseContainerItem", function(...)
	if checkOre then
		itemLink = GetContainerItemLink(...)
		itemID = strmatch(itemLink, "item:(%d*):")
	end
end)
hooksecurefunc("UseItemByName", function(itemName)
	if checkOre then
		itemLink = select(2, GetItemInfo(itemName))
		itemID = strmatch((itemName or ""), "item:(%d*):")
	end
end)

-- hooksecurefunc("CastSpell", function(...)
-- 	if GetSpellInfo(PROSPECT_ID) == GetSpellName(...) or GetSpellInfo(MILLING_ID) == GetSpellName(...) then
-- 		checkOre = 1
-- 	end
-- end)
-- hooksecurefunc("CastSpellByName", function(spellName, onSelf)
-- 	if spellName == PROSPECT or spellName == MILLING then
-- 		checkOre = 1
-- 	end
-- end)

-- DEFAULT_CHAT_FRAME:AddMessage("Prospect: Loaded")
