-- Support for http://www.wowwiki.com/API_GetSellValue

-- localize everything - data retrieval supposed to be high performance function
local ItemDataCache=ItemDataCache
local ItemDataCache_Get_ByID_selltovendor=ItemDataCache.Get.ByID_selltovendor
local type=type
local tonumber=tonumber
local match=string.match
local GetItemInfo=GetItemInfo

local originalGetSellValue

local function ItemDataCache_GetSellValue(item)
	-- ItemDataCache.Chatback("Entering IDC GetSellValue.")
	local itemID
	local argType=type(item)
	if(argType=="number") then
		-- ItemDataCache.Chatback("Argument is number.")
		itemID = item
	elseif(argType=="string") then
		-- ItemDataCache.Chatback("Argument is string, trying tonumber.")
		itemID = tonumber(item) or tonumber(match(item, "item:(%d+)"))
		if(not itemID) then
			-- ItemDataCache.Chatback("tonumber didn't help, trying extracting ID from GetItemInfo.")
			local _, link = GetItemInfo(item)
			if(not link) then
				 -- ItemDataCache.Chatback("Extract failed - no link.")
				 return
			end
			itemID=tonumber(match(link, "item:(%d+)"))
			if(not itemID) then
				-- ItemDataCache.Chatback("Extract failed - no match.")
				return
			end
		end
	else
		-- ItemDataCache.Chatback("Unknown argument type.") 
		return
	end
	local value=ItemDataCache_Get_ByID_selltovendor(itemID)
	if(not value and originalGetSellValue) then
		-- ItemDataCache.Chatback("Value is unknown, trying previous GetSellValue")
		return originalGetSellValue(item)
	end
	-- ItemDataCache.Chatback("Returning from IDC GetSellValue.")
	return value
end

local function OnLoad()
	originalGetSellValue=GetSellValue
	GetSellValue=ItemDataCache_GetSellValue
	-- self-destruct
	OnLoad=nil
end

OnLoad()
