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

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

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

This file is part of nUI.

	The copyright for all material provided within the nUI software package 
	("nUI") is held by Kenneth Scott Piel. Except as stated herein, none of 
	the material may be copied, reproduced, distributed, republished, 
	downloaded, displayed, posted or transmitted in any form or by any means, 
	including, but not limited to, electronic, mechanical, photocopying, 
	recording, or otherwise, without the prior written permission of 
	the copyright holder. Permission is granted to display, copy, distribute 
	and download the materials on this Site for personal, non-commercial use 
	only provided you do not modify the materials and that you retain all 
	copyright and other proprietary notices contained in the materials. You 
	also may not, without the copyright holder's permission, "mirror" any 
	material contained in nUI on any other server. This permission terminates 
	automatically if you breach any of these terms or conditions. Upon 
	termination, you will immediately destroy any downloaded and printed 
	materials. Any unauthorized use of any material contained in nUI may 
	violate copyright laws, trademark laws, the laws of privacy and publicity, 
	and communications regulations and statutes.
	
	nUI is packaged in four distributable versions known as "nUI Release",
	"nUI+", "nUI Development" and "nUI PTR Beta" -- Redistribution for these
	versions is governed by the following terms...
	
	1) Redistribution of the nUI Release (aka nUI Lite) version is permitted under 
	   the following terms... Permission is hereby	granted for unlimited free 
	   and open distribution of "nUI Release" / "nUI Lite" by anyone in any 
	   form and by any means provided the nUI Release distribution contents 
	   are not altered in any way, are distributed in full with all copyright 
	   statements and licensing terms included and intact and that any 
	   interface the end user is provided for the purpose of downloading nUI 
	   includes a plainly visible and functioning link to nUI's official web 
	   site at http://www.nUIaddon.com and a plainly visible notice that nUI 
	   accepts user donations with a working link to nUI's donation page at 
	   http://www.nUIaddon.com/donate.html
	   
	2) Permission is hereby granted for distribution of the "nUI+", "nUI+
	   Development" and "nUI+ PTR Beta" versions of nUI via the online download
	   service at http://www.wowinterface.com and the copyright holder's own
	   web site http://www.nuiaddon.com -- The end user is granted permission
	   to download any nUI package from these two web sites for their personal
	   use under the same terms and conditions as nUI Release but are prohibited
	   from sharing the contents of these packages via any means in any form
	   with anyone other than via direct transfer with immediate friends and
	   family members. Distribution of nUI+, nUI+ Development or nUI+ PTR Beta
	   via any other means by any other entity in any other form is strictly 
	   prohibited without the copyright holder's express written permission
	   explicitly granting such distribution rights specifically to that entity.
	   
	3) Deep-linking and leeching of nUI distributions is strictly prohibited. 
	   Any individual or entity who wishes to offer downloads of nUI 
	   distributions must either host the legal and unmodified distribution 
	   on their own servers to be distributed at their own expense using their 
	   own bandwidth or they must link the user back to the official download 
	   page on the third party provider's servers from which the user can 
	   initiate the download. Use of any download link or mechanism which 
	   initiates a download of any nUI distribution from a third party 
	   distribtion site that bypasses the official content and download pages 
	   or advertisements of that third party site is strictly prohibited
       without the express written consent of that site.
       
    See the included files "nUI_RELEASE_LICENSE.txt" and "nUI_PLUS_LICENSE.txt"
    for the complete terms of nUI's licensing terms.
	   
    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
    enclosed license for more details.
	
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.

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

if not nUI_Profile then nUI_Profile = {}; end;

local CreateFrame         = CreateFrame;
local GetPetActionInfo    = GetPetActionInfo;
local GetPetActionsUsable = GetPetActionsUsable;
local RegisterStateDriver = RegisterStateDriver;
local SetDesaturation     = SetDesaturation;
local UnitIsUnit          = UnitIsUnit;

nUI_Profile.nUI_PetBar = {};

local ProfileCounter = nUI_Profile.nUI_PetBar;

-------------------------------------------------------------------------------
-- the pet bar frame

local anchor     = CreateFrame( "Frame", "nUI_PetBarEvents", WorldFrame );
local frame      = CreateFrame( "Frame", "nUI_PetBar", nUI_Dashboard.Anchor, "SecureFrameTemplate" );

-------------------------------------------------------------------------------
-- button initialization

frame.Buttons = {};

for i=1, NUM_PET_ACTION_SLOTS do

	local button            = CreateFrame( "CheckButton", "$parent_Button"..i, frame, "PetActionButtonTemplate" );	
	local btn_name          = button:GetName();
	frame.Buttons[i]        = button;	
	button.enabled          = true;
	button.layers           = {};
	button.layers.icon      = _G[btn_name.."Icon"];
	button.layers.cooldown  = _G[btn_name.."Cooldown"];
	button.layers.castable  = _G[btn_name.."AutoCastable"];
	button.layers.autocast  = _G[btn_name.."Shine"];	
	button.actionType       = "BONUSACTIONBUTTON";
	button.actionID         = i;
	
	button:SetID( i );
	button:SetNormalTexture( "" );
	frame:SetAttribute( "addchild", button );

	button.SetNormalTexture = function() end;	
	
	button.layers.castable:Show();
	button.layers.autocast:Show();
	
end

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

frame.applyScale = function( scale )
	
--	nUI_ProfileStart( ProfileCounter, "applyScale" );
	
	local scale   = scale or frame.scale or 1;
	local options = frame.options;
	
	if options and options.enabled then
		
		local btn_hSize = options.btn_size * scale * nUI.hScale;
		local btn_vSize = options.btn_size * scale * nUI.vScale;
		local btn_hGap  = (options.btn_gap or 0) * scale * nUI.hScale;
		local btn_vGap  = (options.btn_gap or 0) * scale * nUI.vScale;
		
		if frame.btn_hSize ~= btn_hSize 
		or frame.btn_vSize ~= btn_vSize
		or frame.btn_hGap  ~= btn_hGap
		or frame.btn_vGap  ~= btn_vGap
		then
			
			frame.btn_hSize = btn_hSize;
			frame.btn_vSize = btn_vSize;
			frame.btn_hGap  = btn_hGap;
			frame.btn_vGap  = btn_vGap;
			
			for i=1,#frame.Buttons do
				
				local button = frame.Buttons[i];
				
				button:ClearAllPoints();
				button:SetHeight( btn_vSize );
				button:SetWidth( btn_hSize );
				button:SetScale( 1 );

				button.layers.castable:SetHeight( btn_vSize * 2 );
				button.layers.castable:SetWidth( btn_hSize * 2 );

				button.layers.autocast:SetHeight( btn_vSize * 0.8 );
				button.layers.autocast:SetWidth( btn_hSize * 0.8 );
				
--				button:SetScale( btn_size / button:GetHeight() );
				
				if i == 1 then button:SetPoint( "TOPLEFT", frame, "TOPLEFT", 0, 0 );
				else button:SetPoint( "LEFT", frame.Buttons[i-1], "RIGHT", btn_hGap, 0 );
				end
				
			end
						
			local width = btn_hSize * NUM_PET_ACTION_SLOTS + btn_hGap * (NUM_PET_ACTION_SLOTS-1);
			
			if frame.width ~= width then
				frame.width = width;
				frame:SetHeight( btn_vSize );
				frame:SetWidth( width );
				frame:SetAttribute( "nUI_Width", width );
			end			
		end
	end
	
--	nUI_ProfileStop();
	
end
-------------------------------------------------------------------------------

frame.applyOptions = function( options )

--	nUI_ProfileStart( ProfileCounter, "applyOptions" );
	
	frame.options = options;
	
	if options and options.enabled then

		frame:SetParent( nUI_SpecialBars );
		frame:SetFrameStrata( nUI_SpecialBars:GetFrameStrata() );
		frame:SetFrameLevel( nUI_SpecialBars:GetFrameLevel()+1 );
		
		for i=1, #frame.Buttons do
			
			local button = frame.Buttons[i];
			button:SetFrameStrata( frame:GetFrameStrata() );
			button:SetFrameLevel( frame:GetFrameLevel()+1 );
		end
		
		frame.enabled = true;
	
		frame.applyScale( options.scale or frame.scale or 1 );
		
	end
	
--	nUI_ProfileStop();
	
end

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

frame.updateState = function( index )
	
--	nUI_ProfileStart( ProfileCounter, "updateState" );	
	
	local button = frame.Buttons[index];
	local petActionsUsable = GetPetActionsUsable();
	local name, subtext, texture, isToken, isActive, 
	      autoCastAllowed, autoCastEnabled = GetPetActionInfo( index );
	
	if not isToken then
		button.layers.icon:SetTexture( texture );
		button.tooltipName = name;
	else
		button.layers.icon:SetTexture( getglobal( texture ) );
		button.tooltipName = getglobal( name );
	end
	
	button.isToken        = isToken;
	button.tooltipSubtext = subtext;
	
	if isActive then button:SetChecked( 1 );
	else button:SetChecked( 0 );
	end
	
	if name then 

		if not button.enabled then			
			button.enabled = true;
			button:SetAlpha( 1 );
		end
		
		if autoCastAllowed then button.layers.castable:SetAlpha( 1 ); 
		else button.layers.castable:SetAlpha( 0 ); 
		end
		
		if autoCastEnabled then AutoCastShine_AutoCastStart( button.layers.autocast );
		else AutoCastShine_AutoCastStop( button.layers.autocast );
		end
		
		if texture then
			
			if petActionsUsable then
				SetDesaturation( button.layers.icon, nil );
			else
				SetDesaturation( button.layers.icon, 1 );
			end
			
			button.layers.icon:SetAlpha( 1 );
			
		else
			
			button.layers.icon:SetAlpha( 0 );
			
		end

	elseif button.enabled then

		button.enabled = false;
		button:SetAlpha( 0 );
		button.layers.castable:SetAlpha( 0 );
--		button.layers.autocast:SetAlpha( 0 );
		button.layers.icon:SetAlpha( 0 );
		
	end	
	
--	nUI_ProfileStop();
	
end

-------------------------------------------------------------------------------
-- manage the layout of the bar

anchor:SetScript( "OnEvent", 

	function() 

--		nUI_ProfileStart( ProfileCounter, "OnEvent", event );
	
		local update_state = false;
		
		if event == "UNIT_PET" 
		then
			
			if UnitIsUnit( arg1, "player" ) 
			then update_state = true;
			end
			
		elseif event == "UNIT_FLAGS"
		or     event == "UNIT_AURA"
		then
			
			if UnitIsUnit( arg1, "pet" )
			then update_state = true;
			end
			
		else
			
			update_state = true;

		end
		
		if update_state then
			for i=1, #frame.Buttons do
				frame.updateState( i );
			end
		end		
		
		if event == "PLAYER_ENTERING_WORLD"
		or event == "PET_BAR_UPDATE"
		then
			
			frame.applyScale();
			
		end
		
--		nUI_ProfileStop();
		
	end 
);

anchor:RegisterEvent( "PLAYER_ENTERING_WORLD" );
anchor:RegisterEvent( "PLAYER_CONTROL_LOST" );
anchor:RegisterEvent( "PLAYER_CONTROL_GAINED" );
anchor:RegisterEvent( "PLAYER_FARSIGHT_FOCUS_CHANGED" );
anchor:RegisterEvent( "PET_BAR_UPDATE" );
anchor:RegisterEvent( "UNIT_PET" );
anchor:RegisterEvent( "UNIT_FLAGS" );
anchor:RegisterEvent( "UNIT_AURA" );
