------------------------------------------------
-- Helper functions for the IconDb-Library Addon
-- IconDb is an addon that contains all icons of the game (version 3.0.0.28)
-- Created by Tycere on 10/12/2011
------------------------------------------------
local texturePathMapping = { }
Global("iconDb", { })
-- Parse the group and name from the path
function iconDb.GetGroupAndName(path)
  local p = path
  p = string.gsub(p, "Interface/", "", 1)
  p = string.gsub(p, ".xdb", "", 1)
  p = string.gsub(p, "[.][(]UITexture[)]", "", 1)
  p = string.gsub(p, "[.][(]Texture[)]", "", 1)
  local split = string.split(p, "/")
  local size = GetTableSize(split)
  local group = ""
  for i = 1, size-1 do
    if i == 1 then
	  group = split[i]
	else
      group = group .. "_" .. split[i]
	end
  end
  return group, split[size]
end
-- Request IconDb for the textureId of the texture path
-- params:
--   path: string - The texture path (you can get it from common.GetTexturePath(textureId))
--   callback: function(textureId or nil) - A callback function with one parameter.
--                                          The Parameter can be a textureId or nil.
-- example:
--  iconDb.GetTexture("Interface/Icons/Spells/Mage/MageClairvoyance.(UITexture).xdb", function(texture) 
--    myPanel:SetBackgroundTexture(texture)
--  end)
function iconDb.GetTexture(path, callback)
  path = texturePathMapping[path] or path
  if path and type(path) == "string" and callback then
    local group, name = iconDb.GetGroupAndName(path)
	local responseHandler = nil
	responseHandler = function(params)
	  if params.group == group and params.name == name then
	    common.UnRegisterEventHandler(responseHandler, "SCRIPT_RESPONSE_ICON_" .. common.GetAddonName())
		if params.texture then
		  texturePathMapping[common.GetTexturePath(params.texture)] = path
		end
	    callback(params.texture)
	  end
	end
	common.RegisterEventHandler(responseHandler, "SCRIPT_RESPONSE_ICON_" .. common.GetAddonName())
	userMods.SendEvent("SCRIPT_REQUEST_ICON", 
	  { sender = common.GetAddonName(), group = group, name = name })
  end
end

function iconDb.GetTexturePath(textureId)
  local texturePath = common.GetTexturePath and common.GetTexturePath(textureId) or nil
  return texturePathMapping[texturePath] or texturePath
end