local revision = tonumber(("$Revision: 25398 $"):sub(12, -3))
if revision > Cartographer.revision then
	Cartographer.version = "r" .. revision
	Cartographer.revision = revision
	Cartographer.date = ("$Date: 2007-01-16 04:48:59 -0500 (Tue, 16 Jan 2007) $"):sub(8, 17)
end

local L = AceLibrary("AceLocale-2.2"):new("Cartographer-InstanceNotesLoot")
L:RegisterTranslations("enUS", function() return {
	["Instance Loot"] = true,
	
	["Display of loot on instance bosses."] = true,
	["Left side"] = true,
	["Right side"] = true,
	["Toggle side to display loot info"] = true,
	["Query_Warning"] = "Item not found, click to query server. |cFFFF2222WARNING: This WILL disconnect you if the server has not seen the item.",
} end)

L:RegisterTranslations("deDE", function() return {
	["Instance Loot"] = "Instanzloot",
	
	["Display of loot on instance bosses."] = "Zeigt den Loot der Instanzbosse an.",
	["Left side"] = "Links",
	["Right side"] = "Rechts",
	["Toggle side to display loot info"] = "W\195\164hle Seite zur Anzeige der Lootinformationen.",
	["Query_Warning"] = "Gegenstand nicht gefunden, klicken um den Gegenstand beim Server abzufragen. |cFFFF2222WARNUNG: Das WIRD Deine Serververbindung trennen, wenn der Server den Gegenstand noch nicht kennt.",
} end)

L:RegisterTranslations("frFR", function() return {
	["Instance Loot"] = "Butin d'instance",

	["Display of loot on instance bosses."] = "Affiche le butin des boss d'instance.",
	["Left side"] = "Côté gauche",
	["Right side"] = "Côté droit",
	["Toggle side to display loot info"] = "Détermine le côté où afficher les informations sur le butin.",
	["Query_Warning"] = "Objet introuvable, cliquez pour lancer une requête au serveur. |cFFFF2222ATTENTION : ceci vous déconnectera si le serveur n'a encore jamais vu cet objet.",
} end)

L:RegisterTranslations("koKR", function() return {
	["Instance Loot"] = "인스턴스 획득품",
	
	["Display of loot on instance bosses."] = "인스턴스 보스의 획득품을 표시합니다.",
	["Left side"] = "좌측 사이드",
	["Right side"] = "우측 사이드",
	["Toggle side to display loot info"] = "획득품 정보를 표시할 사이드를 선택합니다.",
	["Query_Warning"] = "Item not found, click to query server. |cFFFF2222WARNING: This WILL disconnect you if the server has not seen the item.",
} end)

L:RegisterTranslations("esES", function() return {
	["Instance Loot"] = "Bot\195\173n de Instancia",
	
	["Display of loot on instance bosses."] = "Muestra el bot\195\173n de los bosses de instancia",
	["Left side"] = "Lado izquierdo",
	["Right side"] = "Lado derecho",
	["Toggle side to display loot info"] = "Determina en qu\195\169 lado se muestra la informaci\195\179n del bot\195\173n",
	["Query_Warning"] = "Objeto no encontrado, clic para preguntar al servidor. |cFFFF2222AVISO: Esto te DESCONECTAR\195\129 si el servidor no ha visto el objeto.",
} end)

L:RegisterTranslations("zhTW", function() return {
	["Instance Loot"] = "副本掉落",
	
	["Display of loot on instance bosses."] = "顯示副本首領的掉落物。",
	["Left side"] = "左側",
	["Right side"] = "右側",
	["Toggle side to display loot info"] = "切換顯示掉落物資訊的位置",
	["Query_Warning"] = "找不到此物品，點擊這裡向伺服器查詢。|cFFFF2222警告: 如果伺服器未曾發現此物品，將會造成您斷線。",
} end)

Cartographer_InstanceLoot = Cartographer:NewModule("InstanceLoot", "AceEvent-2.0", "AceHook-2.1")

local boss
local qualitycolors = {
	[0] = "|cff9d9d9d",
	[1] = "|cffffffff",
	[2] = "|cff1eff00",
	[3] = "|cff0070dd",
	[4] = "|cffa335ee",
	[5] = "|cffff8000"
}
local BB = AceLibrary("Babble-Boss-2.2")
local Tablet = AceLibrary("Tablet-2.0")

function Cartographer_InstanceLoot:OnInitialize()
	self.db = Cartographer:AcquireDBNamespace("InstanceLoot")
	Cartographer:RegisterDefaults("InstanceLoot", "profile", {
		side = "LEFT",
	})
	self.name = L["Instance Loot"]
	self.title = L["Instance Loot"]
	Cartographer.options.args.InstanceLoot = {
		name = L["Instance Loot"],
		desc = L["Display of loot on instance bosses."],
		type = 'group',
		args = {
			toggle = {
				name = AceLibrary("AceLocale-2.2"):new("Cartographer")["Enabled"],
				desc = AceLibrary("AceLocale-2.2"):new("Cartographer")["Suspend/resume this module."],
				type = "toggle",
				order = -1,
				get = function() return Cartographer:IsModuleActive(self) end,
				set = function() Cartographer:ToggleModuleActive(self) end
			},
			side = {
				name = L["Left side"],
				desc = L["Toggle side to display loot info"],
				type = "toggle",
				get = function() return self.db.profile.side == "LEFT" end,
				set = function(v)
					local side = v and "LEFT" or "RIGHT"
					local opposite = v and "RIGHT" or "LEFT"
					self.db.profile.side = side
					Cartographer:ReleaseSideTablet(opposite, self)
					if not boss then
						return
					end
					Cartographer:AcquireSideTablet(side, self)
				end,
				guiNameIsMap = true,
				map = {
					[true] = L["Left side"],
					[false] = L["Right side"],
				}
			},
		},
		handler = self,
	}
	
	CreateFrame("GameTooltip","Cartographer_InstanceLootTooltip",UIParent,"GameTooltipTemplate")
	Cartographer_InstanceLootTooltip:SetWidth(1)
	Cartographer_InstanceLootTooltip:SetHeight(1)
end

function Cartographer_InstanceLoot:OnEnable()
	self:RegisterEvent("Cartographer_SetCurrentInstance")
	self:RegisterEvent("Cartographer_MapClosed")
	if Cartographer:GetCurrentInstance() then
		self:ScheduleEvent("CartographerLoot_ZoneHooks", Cartographer_InstanceLoot.SetZone, 0.4)
	end
end

function Cartographer_InstanceLoot:OnDisable()
	Cartographer:ReleaseSideTablet("LEFT", self)
	Cartographer:ReleaseSideTablet("RIGHT", self)
end

function Cartographer_InstanceLoot:Cartographer_SetCurrentInstance(zone)
	if zone then
		self:ScheduleEvent("CartographerLoot_ZoneHooks", Cartographer_InstanceLoot.SetZone, 0.4)
	else
		self:Cartographer_MapClosed()
	end
end

function Cartographer_InstanceLoot:Cartographer_MapClosed()
	Cartographer_InstanceLoot:UnhookAll()
	Cartographer:ReleaseSideTablet("LEFT", self)
	Cartographer:ReleaseSideTablet("RIGHT", self)
end

function Cartographer_InstanceLoot:SetZone()
	local i = 1
	while getglobal("CartographerNotesPOI"..i) do
		local note = getglobal("CartographerNotesPOI"..i)
		if note.creator == "InstanceNotes" and ((Cartographer_InstanceLoot.hooks and not Cartographer_InstanceLoot.hooks[note]) or not Cartographer_InstanceLoot.hooks) then
			Cartographer_InstanceLoot:HookScript(note, "OnClick")
		end
		i = i + 1
	end
end

function Cartographer_InstanceLoot:OnClick(object, mouseButton)
	if mouseButton == "LeftButton" and object.title and BB:HasReverseTranslation(object.title) then
		Cartographer_InstanceLoot:MakeSideTablet(object.title)
	end
	return Cartographer_InstanceLoot.hooks[object].OnClick(object, mouseButton)
end

function Cartographer_InstanceLoot:MakeSideTablet(title)
	local old_boss = boss
	boss = BB:GetReverseTranslation(title)
	
	if boss == old_boss then
		Cartographer:ReleaseSideTablet(self.db.profile.side, self)
		boss = nil
	else
		Cartographer:AcquireSideTablet(self.db.profile.side, self) -- also refreshes
	end
end

function Cartographer_InstanceLoot:OnTabletRequest()
	if not boss then
		return
	end
	local drops = AceLibrary("PeriodicTable-3.0"):GetSetTable("InstanceLoot." .. Cartographer:GetCurrentEnglishZoneName() .. "." .. boss)
	if not drops then
		return
	end
	Tablet:SetTitle(boss)
	local cat = Tablet:AddCategory('columns', 2)
	local sorted
	--this is kinda an ugly sort.
	for k,v in pairs(drops) do
		if not sorted then
			sorted = {k}
		else
			local stop
			for a,b in pairs(sorted) do
				if not stop and v > drops[b] then
					table.insert(sorted,a,k)
					stop = true
				end
			end
			if not stop then
				table.insert(sorted,k)
			end
		end
	end
	for k,v in pairs(sorted) do
		local name, link, rarity, _,_,_,_,_,_, texture = GetItemInfo(tonumber(v))
		if not link then
			cat:AddLine(
				'text', "|cFFFF2222["..v.."]",
				'text2', ("%.1f%%"):format(drops[v]/10),
				'func', Cartographer_InstanceLoot.DropClick,
				'arg1', self, 'arg2', v
			)
		else
			cat:AddLine(
				'text', qualitycolors[rarity].."["..name.."]",
				'text2', ("%.1f%%"):format(drops[v]/10),
				'func', Cartographer_InstanceLoot.DropClick,
				'arg1', self, 'arg2', v,
				'hasCheck', true,
    			'checked', true,
    			'checkIcon', texture
			)
		end
	end
end
Cartographer_InstanceLoot.OnCartographerLeftTabletRequest = Cartographer_InstanceLoot.OnTabletRequest
Cartographer_InstanceLoot.OnCartographerRightTabletRequest = Cartographer_InstanceLoot.OnTabletRequest

function Cartographer_InstanceLoot:DropClick(id)
	local name, link, rarity, _,_,_,_,_,_, texture = GetItemInfo(id)
	if not name then
		Cartographer_InstanceLootTooltip:SetOwner(this, "ANCHOR_PRESERVE")
		Cartographer_InstanceLootTooltip:SetHyperlink("item:" .. id)
		Cartographer_InstanceLootTooltip:Hide()
		Cartographer_InstanceLoot:ScheduleEvent(function() Cartographer:RefreshSideTablet(self.db.profile.side,Cartographer_InstanceLoot) end,1)
		return
	end
	if IsControlKeyDown() then
		DressUpItem(id)
	elseif IsShiftKeyDown() then
		if not ChatFrameEditBox:IsVisible() then
			ChatFrameEditBox:Show()
		end
		ChatFrameEditBox:Insert(link)
	else
		ShowUIPanel(ItemRefTooltip)
		if not ItemRefTooltip:IsVisible() then
			ItemRefTooltip:SetOwner(UIParent, "ANCHOR_PRESERVE")
		end
		ItemRefTooltip:SetHyperlink(link)
	end
end
