--[[---------------------------------------------------------------------------

Copyright (c) 2008 by K. Scott Piel 
All Rights Reserved

E-mail: < kscottpiel@gmail.com >
Web:    < http://www.scottpiel.com >

This file is part of nUI.

    nUI is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    nUI is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with nUI.  If not, see <http://www.gnu.org/licenses/>.
	
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

-------------------------------------------------------------------------------

Unit Skinning Options: Class

class options =
{
	string strata				-- the frame strata to use (BACKGROUND, LOW, HIGH, etc.) or nil to use the parent frame's strata
	float size					-- height and width of the frame
	int level					-- the frame level to use (1-9) or nil to use the parent frame's level+1
	
	class border				-- sets the frame's border and background or nil for no border/background at all
	{
		class backdrop			-- description of the backdrop itself
		{
			string bgFile		-- path to the frame background texture or nil for no background
			string edgeFile		-- path to the frame edge texture file or nil for no frame edge
			boolean tile		-- true if the background texture should be tiled to fill the frame
			float tileSize		-- size of each background tile
			float edgeSize		-- thickness of the edge texture around the frame
			
			class insets = 
			{	
				int left		-- inset of background texture from the outside edges of the frame
				int right
				int top
				int bottom
			};
		};
		
		class color
		{
			class border = { r, g, b, a }	-- color and transparency of the edge texture
			class backdrop = { r, g, b, a }	-- color and transparency of the background texture
		};
	};
}

--]]---------------------------------------------------------------------------

if not nUI then nUI = {}; end
if not nUI_Unit then nUI_Unit = {}; end
if not nUI_UnitOptions then nUI_UnitOptions = {}; end
if not nUI_DefaultConfig then nUI_DefaultConfig = {}; end

local GetTime   = GetTime;
local UnitClass = UnitClass;

-------------------------------------------------------------------------------
-- default options for the unit class colors

nUI_DefaultConfig.ClassColors =
{
	["UNKNOWN"] = { r = 1, g = 1, b = 1, },
	["WARRIOR"] = { r = RAID_CLASS_COLORS["WARRIOR"].r, g = RAID_CLASS_COLORS["WARRIOR"].g, b = RAID_CLASS_COLORS["WARRIOR"].b },
	["MAGE"]    = { r = RAID_CLASS_COLORS["MAGE"].r, g = RAID_CLASS_COLORS["MAGE"].g, b = RAID_CLASS_COLORS["MAGE"].b },
	["ROGUE"]   = { r = RAID_CLASS_COLORS["ROGUE"].r, g = RAID_CLASS_COLORS["ROGUE"].g, b = RAID_CLASS_COLORS["ROGUE"].b },
	["DRUID"]   = { r = RAID_CLASS_COLORS["DRUID"].r, g = RAID_CLASS_COLORS["DRUID"].g, b = RAID_CLASS_COLORS["DRUID"].b },
	["HUNTER"]  = { r = RAID_CLASS_COLORS["HUNTER"].r, g = RAID_CLASS_COLORS["HUNTER"].g, b = RAID_CLASS_COLORS["HUNTER"].b },
	["SHAMAN"]  = { r = RAID_CLASS_COLORS["SHAMAN"].r, g = RAID_CLASS_COLORS["SHAMAN"].g, b = RAID_CLASS_COLORS["SHAMAN"].b },
	["PRIEST"]  = { r = RAID_CLASS_COLORS["PRIEST"].r, g = RAID_CLASS_COLORS["PRIEST"].g, b = RAID_CLASS_COLORS["PRIEST"].b },
	["WARLOCK"] = { r = RAID_CLASS_COLORS["WARLOCK"].r, g = RAID_CLASS_COLORS["WARLOCK"].g, b = RAID_CLASS_COLORS["WARLOCK"].b },
	["PALADIN"] = { r = RAID_CLASS_COLORS["PALADIN"].r, g = RAID_CLASS_COLORS["PALADIN"].g, b = RAID_CLASS_COLORS["PALADIN"].b },
};

-------------------------------------------------------------------------------
-- pre-calculated locations for class information

local ClassInfo =
{
	["UNKNOWN"] = 
	{ 
		color = nUI_DefaultConfig.ClassColors["UNKNOWN"],
		row   = 2,
		col   = 3,
		x1    = 0.75,
		x2    = 1,
		y1    = 0.5,
		y2    = 0.75,
	},
	["WARRIOR"] = 	
	{ 
		color = nUI_DefaultConfig.ClassColors["WARRIOR"],
		row   = 0,
		col   = 0,
		x1    = 0,
		x2    = 0.25,
		y1    = 0,
		y2    = 0.25,
	},
	["MAGE"] = 
	{ 
		color = nUI_DefaultConfig.ClassColors["MAGE"],
		row   = 0,
		col   = 1,
		x1    = 0.25,
		x2    = 0.5,
		y1    = 0,
		y2    = 0.25,
	},
	["ROGUE"] = 
	{ 
		color = nUI_DefaultConfig.ClassColors["ROGUE"],
		row   = 0,
		col   = 2,
		x1    = 0.5,
		x2    = 0.75,
		y1    = 0,
		y2    = 0.25,
	},
	["DRUID"]   = 
	{ 
		color = nUI_DefaultConfig.ClassColors["DRUID"],
		row   = 0,
		col   = 3,
		x1    = 0.75,
		x2    = 1,
		y1    = 0,
		y2    = 0.25,
	},
	["HUNTER"]  = 
	{ 
		color = nUI_DefaultConfig.ClassColors["HUNTER"],
		row   = 1,
		col   = 0,
		x1    = 0,
		x2    = 0.25,
		y1    = 0.25,
		y2    = 0.5,
	},
	["SHAMAN"]  = 
	{ 
		color = nUI_DefaultConfig.ClassColors["SHAMAN"],
		row   = 1,
		col   = 1,
		x1    = 0.25,
		x2    = 0.5,
		y1    = 0.25,
		y2    = 0.5,
	},
	["PRIEST"]  = 
	{ 
		color = nUI_DefaultConfig.ClassColors["PRIEST"],
		row   = 1,
		col   = 2,
		x1    = 0.5,
		x2    = 0.75,
		y1    = 0.25,
		y2    = 0.5,
	},
	["WARLOCK"] = 
	{ 
		color = nUI_DefaultConfig.ClassColors["WARLOCK"],
		row   = 1,
		col   = 3,
		x1    = 0.75,
		x2    = 1,
		y1    = 0.25,
		y2    = 0.5,
	},
	["PALADIN"] = 
	{ 
		color = nUI_DefaultConfig.ClassColors["PALADIN"],
		row   = 2,
		col   = 0,
		x1    = 0,
		x2    = 0.25,
		y1    = 0.5,
		y2    = 0.75,
	},
};

-------------------------------------------------------------------------------
-- unit class event management

if not nUI_Unit.Drivers then 
	nUI_Unit.Drivers = CreateFrame( "Frame", "nUI_UnitDrivers", WorldFrame ); 
end

local frame = CreateFrame( "Frame", "$parent_Class", nUI_Unit.Drivers )

local ClassCallbacks    = {};
local ClassUnits        = {};

nUI_Unit.Drivers.Class  = frame;

-------------------------------------------------------------------------------

local function onClassEvent()
	
	if event == "VARIABLES_LOADED" then
		
		nUI:registerSkinnedFrame( frame );
		
	-- for these events, we don't know which units are affected, so
	-- we span the list of all known interested units to see who is watching
		
	elseif event == "PLAYER_ENTERING_WORLD" then
		
		nUI_Unit:refreshClassCallbacks();
		
	end
end

frame:SetScript( "OnEvent", onClassEvent );
frame:RegisterEvent( "VARIABLES_LOADED" );
frame:RegisterEvent( "PLAYER_ENTERING_WORLD" );

-------------------------------------------------------------------------------
-- this callback method is called when one of the unit IDs we are monitoring
-- for unit class changes GUID

frame.newUnitInfo = function( list_unit, unit_info )

	local new_data  = nUI_Unit:updateClassInfo( list_unit, unit_info );
	local callbacks = ClassCallbacks;
	local unitlist  = ClassUnits;
	
	nUI_Unit:notifyCallbacks( nUI_L["unit class"], callbacks, unitlist, unit_info, list_unit, new_data );
	
end

-------------------------------------------------------------------------------

frame.applySkin = function( skin )

	nUI_UnitOptions.ClassColors = skin.ClassColors or nUI_Default_Config.ClassColors;
	
end

-------------------------------------------------------------------------------
-- initialize configuration for the unit class color indicators
-- 
-- this method is called when the mod's saved variables have been loaded by Bliz and
-- may be called again whenever the unit class configuration has been changed
-- by the player or programmatically. Passing true or a non-nil value for "use_default"
-- will cause the player's current class color configuration to be replaced with
-- the default settings defined at the top of this file (which cannot be undone!)

function nUI_Unit:configClass( use_default )
	
	if not nUI_UnitOptions then nUI_UnitOptions = {}; end
	if not nUI_UnitOptions.ClassColors then nUI_UnitOptions.ClassColors = {}; end
	
	local config  = nUI_UnitOptions.ClassColors;
	local default = nUI_DefaultConfig.ClassColors;
	
	for class in pairs( default ) do
		nUI_Unit:configClassColor( class, use_default );
	end
end

function nUI_Unit:configClassColor( class, use_default )
	
	local config  = nUI_UnitOptions.ClassColors[class] or {};
	local default = nUI_DefaultConfig.ClassColors[class] or {};
	
	if use_default then
			
		config.r = default.r;
		config.g = default.g;
		config.b = default.b;

	else
			
		config.r = tonumber( config.r or default.r );
		config.g = tonumber( config.g or default.g );
		config.b = tonumber( config.b or default.b );

	end
	
	nUI_UnitOptions.ClassColors[class] = config;
	ClassInfo[class].color = config;
		
	nUI_Unit:refreshClassCallbacks();
	
end

-------------------------------------------------------------------------------
-- add and remove callbacks from the list of unit class listeners we manage
--
-- calling this method will return the current unit_info structure for this 
-- unit if it exists or nil if the unit does not exist at this time
--
-- Note: these callbacks will be notified both when the underlying GUID for the
--		 unit changes or when the class info of the underlying GUID to the
--		 player changes. If the underlying unit does not exist, the callback
--		 will be passed a nil unit_info structure

function nUI_Unit:registerClassCallback( unit_id, callback )
	
	local unit_info = nil;
	
	if unit_id and callback then
		
		-- get the list of callbacks for this unit id and add this callback
		
		local list = ClassCallbacks[unit_id] or {};
		
		nUI:TableInsertByValue( list, callback );
		
		-- if this is a new unit id, add it to the callback list
		
		if not ClassCallbacks[unit_id] then
			ClassCallbacks[unit_id] = list;
		end
		
		-- if this is the first callback for the unit id, then register our
		-- event driver to receive notice when the GUID changes on this id
		
		if #list == 1 then
			nUI_Unit:registerUnitChangeCallback( unit_id, nUI_Unit.Drivers.Class );
		end
		
		-- collect class information for this unit as we know it at this time
	
		unit_info = nUI_Unit:getUnitInfo( unit_id );
		
		if unit_info then
			nUI_Unit:updateClassInfo( unit_id, unit_info );
		end
	end
	
	return unit_info;
	
end

function nUI_Unit:unregisterClassCallback( unit_id, callback )
	
	if unit_id and callback then
		
		-- get the list of current callbacks for this unit ud and remove this callback
		
		local list = ClassCallbacks[unit_id] or {};
		
		nUI:TableRemoveByValue( list, callback );
		
		-- if that's the last callback in the list, then remove our event handler of
		-- the list of unit change callbacks for that unit it
		
		if #list == 0 then
			nUI_Unit:unregisterUnitChangeCallback( unit_id, nUI_Unit.Drivers.Class );
		end
	end
end

-------------------------------------------------------------------------------
-- update the class information for this unit
--
-- note: it is the caller's responsibility to ensure that the unit_info being
--       passed belongs to the unit_id that is passed. Generally third party
--       consumers of unit_info should not call this method, rather they 
--       should use the callback registration system to get change notices
--       and let the nUI unit driver engine do the updating. If you MUST call
--       this method, you should first test that the following condition 
--       evaluates as true: UnitGUID( unit_id ) == unit_info.guid
--
-- returns the updated unit information structure for the current GUID
-- if the data has changed, otherwise returns nil if nothing changed

function nUI_Unit:updateClassInfo( unit_id, unit_info )

	local modified  = false;
	
	if unit_info then
		
		local class_name, class = UnitClass( unit_id );
		
		if unit_info.class      ~= class 
		or unit_info.class_name ~= class_name
		then
			
			modified              = true;
			unit_info.modified    = true;
			unit_info.last_change = GetTime();
			unit_info.class       = class;
			unit_info.class_name  = class;

			-- which icon applies to this class?
			
			if class == "WARRIOR" then 
				unit_info.class_info = ClassInfo[class];
			elseif class == "MAGE" then
				unit_info.class_info = ClassInfo[class];
			elseif class == "ROGUE" then
				unit_info.class_info = ClassInfo[class];
			elseif class == "DRUID" then
				unit_info.class_info = ClassInfo[class];
			elseif class == "HUNTER" then
				unit_info.class_info = ClassInfo[class];
			elseif class == "SHAMAN" then
				unit_info.class_info = ClassInfo[class];
			elseif class == "PRIEST" then
				unit_info.class_info = ClassInfo[class];
			elseif class == "WARLOCK" then
				unit_info.class_info = ClassInfo[class];
			elseif class == "PALADIN" then
				unit_info.class_info = ClassInfo[class];
			else
				unit_info.class_info = ClassInfo["UNKNOWN"];
				if class then DEFAULT_CHAT_FRAME:AddMessage( nUI_L["nUI_UnitClass.lua: unhandled unit class [%s] for [%s]"]:format( class, unit_id ), 1, 0.5, 0.5 ); end
			end
			
			local color = unit_info.class_info.color;
			local color2 = RAID_CLASS_COLORS["HUNTER"];
		end
	end
	
	return modified and unit_info or nil;
	
end

-------------------------------------------------------------------------------
-- update all of the registered unit class listeners, even if there's no 
-- change in data... typically used when the class color options change
-- or entering the world

function nUI_Unit:refreshClassCallbacks()

	nUI_Unit:refreshCallbacks( 
	
		nUI_L["unit class"], ClassCallbacks, ClassUnits, 
	
		function( list_unit, unit_info ) 
			nUI_Unit:updateClassInfo( list_unit, unit_info ); 
		end 
	);

end

-------------------------------------------------------------------------------
-- create a new unit class frame

function nUI_Unit:createClassFrame( parent, unit_id, id, options, clickable )

	local frame   = nUI_Unit:createFrame( "$parent_Class"..(id or ""), parent, unit_id, clickable );	
	frame.texture = frame:CreateTexture( "$parentTexture", "BORDER" );
	frame.Super   = {};
	
	frame.texture:SetPoint( "CENTER", frame, "CENTER", 0, 0 );
	frame.texture:SetTexture( "Interface\\AddOns\\nUI\\Units\\Art\\nUI_Icon_Classes.blp" );

	-- called when the underlying GUID for the unit changes or when the
	-- content of the GUID is updated
	
	frame.Super.newUnitInfo = frame.newUnitInfo;
	frame.newUnitInfo       = function( list_unit, unit_info )
		
		frame.Super.newUnitInfo( list_unit, unit_info );
		
		if frame.enabled then
			nUI_Unit:updateClassFrame( frame );
		end
		
	end
	
	-- setting enabled to false will prevent the frame from updating when new
	-- unit information is received (saves framerate). Setting enabled true will
	-- call the frame to immediately update if its content has changed since it
	-- was disabled

	frame.Super.setEnabled = frame.setEnabled;	
	frame.setEnabled       = function( enabled )
		
		local prior_state = frame.enabled;
		
		frame.Super.setEnabled( enabled );
		
		if frame.enabled ~= prior_state then
		
			if frame.enabled then
				frame.unit_info = nUI_Unit:registerClassCallback( frame.unit, frame );
				nUI_Unit:updateClassFrame( frame );
			else
				nUI_Unit:unregisterClassCallback( frame.unit, frame );
			end
		end
	end
	
	-- used to change the scale of the frame... rather than the Bliz widget frame:SetScale()
	-- this method actually recalculates the size of the frame and uses frame:SetHeight()
	-- and frame:SetWidth() to reflect the actual size of the frame.

	frame.Super.applyScale = frame.applyScale;
	frame.applyScale       = function( scale )
		
		frame.Super.applyScale( scale );
		
		if frame.texture.size   ~= frame.size 
		or frame.texture.width  ~= frame.width
		or frame.texture.height ~= frame.height 
		or frame.texture.inset  ~= frame.inset
		then
			
			frame.texture.size   = frame.size;
			frame.texture.width  = frame.width;
			frame.texture.height = frame.height;
			frame.texture.inset  = frame.inset;
			
			frame.texture:SetWidth( (frame.size or frame.width) - frame.inset );
			frame.texture:SetHeight( (frame.size or frame.height) - frame.inset );

		end
	end
	
	-- applies the set of frame options to this frame. Typically called when the frame 
	-- is first created or when the user changes options via config.
	
	frame.Super.applyOptions = frame.applyOptions;
	frame.applyOptions       = function( options )

		frame.Super.applyOptions( options );		
		nUI_Unit:updateClassFrame( frame );
		
	end

	-- initiate the frame
	
	frame.unit_info = nUI_Unit:registerClassCallback( frame.unit, frame );
	
	frame.applyOptions( options );
	
	return frame;
	
end

-------------------------------------------------------------------------------
-- remove a unit class frame

function nUI_Unit:deleteClassFrame( frame )

	nUI_Unit:unregisterClassCallback( frame.unit, frame );
	nUI_Unit:deleteFrame( frame );
	
end

-------------------------------------------------------------------------------
-- display the appropriate icon for the unit's class
--
-- note: this method expends extra energy in state management... as in knowing
--       exactly what state it is currently in and only updating the frame text,
--       content, colors, alphas, etc. when a change in state occurs. The extra
--       effort is spent on state management in order to reduce impact to the
--       graphis engine so as to preserve frame rate. It costs far less to check
--		 a memory value that and burn through the graphics geometry. It does not
--       matter how many times the unit changes GUID or how many times this 
--       method will call, it will only alter the graphics elements when its
--       relative state changes.

function nUI_Unit:updateClassFrame( frame )
	
	local unit_info = frame.unit_info;
	
	-- if there is no unit or we don't know it's class, then hide the icon
	
	if not unit_info or not unit_info.class then
		
		if frame.active then
			frame.active = false;
			frame.texture:SetAlpha( 0 );
		end
	
	-- otherwise, show the icon and clip the appropriate region
	
	else

		-- if the class icon is hidden, show it
		
		if not frame.active then
			frame.active = true;
			frame.texture:SetAlpha( 1 );
		end

		-- if the class has changed from what we last knew, then update 
		
		if frame.class ~= unit_info.class then
			
			local data = unit_info.class_info;
			
			if data then
				
				local x1 = data.x1;
				local x2 = data.x2;
				local y1 = data.y1;
				local y2 = data.y2;

				frame.class = unit_info.class;
				frame.texture:SetTexCoord( x1, y1, x1, y2, x2, y1, x2, y2 );
			end
		end
	end
end
