--[[--------------------------------------------------------------------------------
	I wanted to Ace2ify Sell Value Lite, ended up stealing it from Ludwig instead.
    (Who stole it from Sell Value Lite :))
-----------------------------------------------------------------------------------]]

local abacus = AceLibrary("Abacus-2.0")
local L = AceLibrary("AceLocale-2.2"):new("ColaLight")

ColaLight = AceLibrary("AceAddon-2.0"):new("AceEvent-2.0", "AceHook-2.1", "AceConsole-2.0", "AceDB-2.0")

ColaLight.latest = 0

--[[--------------------------------------------------------------------------------
    OnInitialize, initializes the mod
-----------------------------------------------------------------------------------]]
function ColaLight:OnInitialize()
	self:RegisterDB("ColaLightDB")
	self:RegisterDefaults('account', {
		SellValues = {},
	})

	local args = {
		type = "group",
		args = {
			purge = {
				name  = "Purge", type = "execute",
				desc  = L["Purges the current databse."],
				func   = function(text) self:PurgeDB() end,
			},
		},
	}
	
	self:RegisterChatCommand({"/colalight", "/cl"}, args)

    CreateFrame("GameTooltip", "ColaLightTooltip", UIParent, "GameTooltipTemplate")
    ColaLightTooltip:SetOwner(UIParent, "ANCHOR_PRESERVE")
end

--[[--------------------------------------------------------------------------------
    OnEnable, enable the mod
-----------------------------------------------------------------------------------]]
function ColaLight:OnEnable()
	self:HookTooltips()
	self:HookScript(ColaLightTooltip, "OnEvent", "MERCHANT_SHOW")
	self:HookScript(ColaLightTooltip, "OnTooltipAddMoney", "CLT_OnTooltipAddMoney")
	ColaLightTooltip:RegisterEvent("MERCHANT_SHOW")
end

--[[--------------------------------------------------------------------------------
    OnDisable, disable the mod
-----------------------------------------------------------------------------------]]
function ColaLight:OnDisable()
	ColaLightTooltip:UnregisterEvent("MERCHANT_SHOW")
end

--[[--------------------------------------------------------------------------------
    Slash command handlers
-----------------------------------------------------------------------------------]]
function ColaLight:PurgeDB()
	self:Print(L["Purging the db..."])
	self.db.account.SellValues = {}
end

--[[--------------------------------------------------------------------------------
    Hooks
-----------------------------------------------------------------------------------]]

local getLinkFunctions = {
	SetLootItem			= GetLootSlotLink,
	SetLootRollItem		= function(id) return GetLootRollItemLink(id) end,
	SetHyperlink		= function(link) return link end,
	SetAuctionItem		= GetAuctionItemLink,
	SetBagItem			= GetContainerItemLink,
	SetCraftItem		= function(skill, id) return id and GetCraftReagentItemLink(skill, id) or GetCraftItemLink(skill) end,
	SetInventoryItem	= function(type, slot) if not this then return end return type and GetInventoryItemLink(type, slot) or GetContainerItemLink(BANK_CONTAINER,this:GetID()) end,
	SetQuestItem		= GetQuestItemLink,
	SetQuestLogItem		= GetQuestLogItemLink,
	SetTradePlayerItem	= GetTradePlayerItemLink,
	SetTradeSkillItem	= function(skill, id) return (id) and GetTradeSkillReagentItemLink(skill, id) or GetTradeSkillItemLink(skill) end,
	SetTradeTargetItem	= GetTradeTargetItemLink,
}

local getQuantityFunctions = {
	SetLootItem			= function(slot) local _,_, count = GetLootSlotInfo(slot); return count; end,
	SetLootRollItem		= function(id) local _, _, count = GetLootRollItemInfo(id); return count end,
	SetHyperlink		= function() return 1 end,
	SetAuctionItem		= function(type, slot) local _,_, count = GetAuctionItemInfo(type, slot); return count; end,
	SetBagItem			= function(bag, slot) local _, count = GetContainerItemInfo(bag, slot); return count;  end,
	SetCraftItem		= function(skill, id) if id then local _, _, count = GetCraftReagentInfo(skill, id); return count else return 1 end end,
	SetInventoryItem	= function(unit, slot) if not this then return end; if unit then return GetInventoryItemCount(unit, slot) else local _, count = GetContainerItemInfo(BANK_CONTAINER,this:GetID()); return count; end end,
	SetQuestItem		= function(type, slot) local _,_, count = GetQuestItemInfo(type, slot); return count; end,
	SetQuestLogItem		= function(type, slot) local _,_, count = GetQuestLogRewardInfo(slot); return count; end,
	SetTradePlayerItem	= function(id) local _,_, count = GetTradeTargetItemInfo(id); return count; end,
	SetTradeSkillItem	= function(skill, id) if id then local _, _, count = GetTradeSkillReagentInfo(skill, id); return count else return 1 end end,
	SetTradeTargetItem	= function(id) local _,_, count = GetTradeTargetItemInfo(id); return count; end,
}

function ColaLight:HookTooltips()
	for o, l in pairs(getLinkFunctions) do
		local originalFunction, linkFunction = o, l  -- Get these into a local context, to avoid errors.  This drove me nuts.
		local quantityFunction = getQuantityFunctions[originalFunction]
		self:Hook(GameTooltip, originalFunction, function(tooltip, arg1, arg2, arg3)
			return1, return2, return3 = self.hooks[tooltip][originalFunction](tooltip, arg1, arg2, arg3)
			self:AddMoneyToTooltip(tooltip, self:LinkToID(linkFunction(arg1, arg2, arg3)), quantityFunction(arg1, arg2, arg3), originalFunction)
			return return1, return2, return3
		end)
	end
end

--[[--------------------------------------------------------------------------------
    OnEvent Handlers
-----------------------------------------------------------------------------------]]

function ColaLight:MERCHANT_SHOW()
	for bag = 0, NUM_BAG_FRAMES do
		for slot = 1, GetContainerNumSlots(bag) do
			local id = self:LinkToID(GetContainerItemLink(bag, slot))
			local _, count = GetContainerItemInfo(bag, slot)
			
			if id and id ~= '' then
				ColaLight.latest = 0
				ColaLightTooltip:SetBagItem(bag, slot)
				self:StoreValue(id, ColaLight.latest, count)
			end
		end
	end
end

--[[--------------------------------------------------------------------------------
    Utility function
-----------------------------------------------------------------------------------]]

function ColaLight:LinkToID(link)
	if link then
		local _, _, id = string.find(link, "(%d+):")
		return id
	end
end

function ColaLight:StoreValue(id, totalCost, count)
	if (count and count > 0 and totalCost) then
		self.db.account.SellValues[id] = totalCost / count
	end
end

function ColaLight:AddMoneyToTooltip(frame, id, count, source)
    if (self.db.account.SellValues and not (MerchantFrame:IsVisible() and source == 'SetBagItem') and count) then
		local price = self.db.account.SellValues[id]
		if price ~= nil then
			if price == 0 then
				frame:AddLine(ITEM_UNSELLABLE, 1.0, 1.0, 0)
			else
				if count > 1 then
					price = abacus:FormatMoneyFull(price, true)..' ('..abacus:FormatMoneyFull(price * count, true)..')'
				else
					price = abacus:FormatMoneyFull(price, true)
				end
				frame:AddDoubleLine(L["Sells for:"], price, 1.0, 1.0, 0)
			end
			frame:Show()
		end
	end
end

function ColaLight:CLT_OnTooltipAddMoney()
	if (not InRepairMode()) then
		ColaLight.latest = arg1
	end
end
