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

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.

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

if not nUI then nUI = {}; end
if not nUI.UnitPanels then nUI.UnitPanels = {}; end
if not nUI.UnitFrame then nUI.UnitFrames = {}; end
if not nUI_UnitPanels then nUI_UnitPanels = {}; end
if not nUI_DefaultConfig then nUI_DefaultConfig = {}; end

local CreateFrame = CreateFrame;

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

nUI_DefaultConfig.UnitPanelSelector =
{
	anchor =
	{
		anchor_pt   = "TOPLEFT",
		relative_to = "nUI_BonusBar1",
		relative_pt = "TOPRIGHT",
		xOfs        = 7,
		yOfs        = 0,
	},
	options =
	{
		enabled = true,
		height  = 40,
		width   = 93,
		strata  = nil,
		level   = nil,
			
		label =
		{
			enabled = true,
			fontsize = 12,
			anchor_pt = "CENTER",
		},
		
		background =
		{
			backdrop =
			{
				bgFile   = "Interface\\Tooltips\\UI-Tooltip-Background", 
				edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", 
				tile     = true, 
				tileSize = 1, 
				edgeSize = 5, 
				insets   = { left = 0, right = 0, top = 0, bottom = 0 },
			},
			
			color =
			{
				border = { r = 1, g = 1, b = 1, a = 1 },
				backdrop = { r = 0.75, g = 0, b = 0, a = 0.75 },
			},
		},		
	},
};

-------------------------------------------------------------------------------
-- method for sorting the unit panel options on the selector button. Panels
-- are ordered ascending first by their rotation number, then by their 
-- description and finally by their panel name.

local function SortPanelList( left, right )

	local result;
	
	if left.rotation > right.rotation then
		result = false;
	elseif left.rotation < right.rotation then
		result = true;
	elseif left.desc > right.desc then
		result = false;
	elseif left.desc < right.desc then
		result = true;
	elseif left.name > right.name then
		result = false;
	else
		result = true;
	end
	
	return result;
	
end

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

local UnitPanelList          = {};

local background = CreateFrame( "Frame", "nUI_UnitPanelBackground", nUI_Dashboard.Anchor );
local frame      = CreateFrame( "Frame", "nUI_UnitPanelSelector", background, "SecureStateHeaderTemplate" );
frame.button     = CreateFrame( "Button", "$parent_Button", frame, "SecureAnchorButtonTemplate" );
frame.text       = frame:CreateFontString( "$parent_Label", "ARTWORK" );

nUI_UnitPanelSelector        = frame;
nUI_UnitPanelSelector.Labels = {};

background:SetAllPoints( frame );
frame.button:SetAllPoints( frame );
frame:SetAttribute( "addchild", frame.button );

frame.button:SetScript( "OnEnter",

	function()
		GameTooltip:SetOwner( frame.button );
		GameTooltip:SetText( frame.desc or nUI_L["Click to change unit frame panels"] );
		if frame.desc then 
			GameTooltip:AddLine( nUI_L["Click to change unit frame panels"] );
		end
		GameTooltip:Show();
	end
);

frame.button:SetScript( "OnLeave", function() GameTooltip:Hide(); end );

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

frame.applyScale = function( scale )
	
	local scale    = scale or frame.scale or 1;
	local options  = frame.options;
	local fontsize = (options and options.label and options.label.fontsize or 12) * nUI.scale * 1.75;
	
	frame.scale   = scale;
	
	if options then
		
		local width  = options.width * scale * nUI.scale;
		local height = options.height * scale * nUI.scale;
		
		if frame.width ~= width
		or frame.height ~= height
		then
			
			frame.width  = width;
			frame.height = height;
			
			frame:SetWidth( width );
			frame:SetHeight( height );
			
		end
	end
	
	if frame.text.fontsize ~= fontsize then
		frame.text.fontsize = fontsize;
		frame.text:SetFont( nUI_L["font1"], fontsize, "OUTLINE" );
	end
	
end

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

frame.applyAnchor = function( anchor )
	
	local anchor      = anchor or frame.anchor or {};
	local anchor_pt   = anchor.anchor_pt or "CENTER";
	local relative_to = anchor.relative_to or "nUI_Dashboard";
	local relative_pt = anchor.relative_pt or "CENTER";
	local xOfs        = (anchor.xOfs or 0) * nUI.scale;
	local yOfs        = (anchor.yOfs or 0) * nUI.scale;
	
	frame.anchor = anchor;
	
	if frame.xOfs ~= xOfs
	or frame.yOfs ~= yOfs
	or frame.anchor_pt ~= anchor_pt
	or frame.relative_to ~= relative_to
	or frame.relative_pt ~= relative_pt
	then
		
		frame.anchor_pt = anchor_pt;
		frame.relative_to = relative_to;
		frame.relative_pt = relative_pt;
		frame.xOfs        = xOfs;
		frame.yOfs        = yOfs;
		
		frame:SetPoint( anchor_pt, relative_to, relative_pt, xOfs, yOfs );
		
	end

	if frame.options then

		local label = frame.options.label;
		
		if label and label.enabled then
			
			anchor_pt   = label.anchor_pt or "CENTER";
			relative_to = label.relative_to or frame:GetName();
			relative_pt = label.relative_pt or anchor_pt;			
			xOfs        = (label.xOfs or 0) * frame.scale * nUI.scale;
			yOfs        = (label.yOfs or 0) * frame.scale * nUI.scale;
			
			if frame.text.xOfs ~= xOfs
			or frame.text.yOfs ~= yOfs
			or frame.text.anchor_pt ~= anchor_pt
			or frame.text.relative_to ~= relative_to
			or frame.text.relative_pt ~= relative_pt
			then
				
				frame.text.anchor_pt   = anchor_pt;
				frame.text.relative_to = relative_to;
				frame.text.relative_pt = relative_pt;
				frame.text.xOfs        = xOfs;
				frame.text.yOfs        = yOfs;
				
				frame.text:SetPoint( anchor_pt, relative_to, relative_pt, xOfs, yOfs );
				
			end			
		end		
	end
end

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

frame.applyOptions = function( options )
	
	frame.options = options;
	
	if not options or not options.enabled then
		
		frame.enabled = false;
		background:Hide();
		
	else
		
		frame.enabled = true;
		background:Show();
		
		background:SetFrameStrata( options.strata or nUI_Dashboard:GetFrameStrata() );
		background:SetFrameLevel( options.level or nUI_Dashboard:GetFrameLevel()+2 );
		
		if not options.label or not options.label.enabled then
			
			frame.text.enabled = false;
			frame.text.value   = nil;
			frame.text:SetAlpha( 0 );
			frame.text:SetText( "" );
			
		else
			
			frame.text.enabled = true;
			frame.text:SetAlpha( 1 );
			
			local color = options.label.color or {};
			
			frame.text:SetTextColor( color.r or 1, color.g or 0.83, color.b or 0, color.a or 1 );
			
		end
		
		if options.border then
			
			local backdrop_color = options.border.color.backdrop;
			local border_color   = options.border.color.border;
			
			frame:SetBackdrop( options.border.backdrop );
			frame:SetBackdropColor( backdrop_color.r, backdrop_color.g, backdrop_color.b, backdrop_color.a );
			frame:SetBackdropBorderColor( border_color.r, border_color.g, border_color.b, border_color.a );
			
		else
			
			frame:SetBackdrop( nil );
			
		end
		
		if options.background then
			
			local backdrop_color = options.background.color.backdrop;
			local border_color   = options.background.color.border;
			
			frame:SetBackdrop( options.background.backdrop );
			frame:SetBackdropColor( backdrop_color.r, backdrop_color.g, backdrop_color.b, backdrop_color.a );
			frame:SetBackdropBorderColor( border_color.r, border_color.g, border_color.b, border_color.a );
			
		end

		frame.applyScale( options.scale or frame.scale or 1 );
	
	end	
end

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

frame.applySkin = function( skin )
	
	-- we don't allow the skin developer to not include unit panels... if they
	-- don't specify them, we use the default
	
	local skin = skin.UnitPanelSelector or nUI_DefaultConfig.UnitPanelSelector;
	
	if not skin or not skin.options.enabled then
		
		frame.enabled = false;
		background:Hide();
		
	else
		
		frame.enabled = true;
		background:Show();

		frame.applyOptions( skin.options );
		frame.applyAnchor( skin.anchor );

		-- spin the list of unit frame panels and create each as required
		
		local have_selection = false;
		
		for panel_name in pairs( nUI_UnitPanels ) do
					
			local panel_config = nUI_UnitPanels[panel_name];
			local panel        = _G[panel_name];
						
			-- if this panel has not been disabled by the player, create it
			
			if not panel_config.enabled then						
				
				if panel then
					
					panel.enabled = false;
					panel:Hide();
					
					for i = #UnitPanelList, 1, -1 do
						if UnitPanelList[i].panel_name == panel_name then
							table.remove( UnitPanelList, i );
							break;
						end
					end
					
					for i = #nUI.UnitPanels, 1, -1 do
						if nUI.UnitPanels[i].panel_name == panel_name then
							table.remove( nUI.UnitPanels, i );
							break;
						end
					end
					
					for i = #UnitPanelSelector.Labels, 1, -1 do
						if nUI_UnitPanelSelector.Labels[i] == panel.label then
							table.remove( nUI_UnitPanelSelector.Labels, i );
							break;
						end
					end
				end

			else
				
				-- create a sort list of panels so we can organize the button rotation
				
				local panel_item = 
				{ 
					name     = panel_name, 
					desc     = panel_config.desc,
					rotation = panel_config.rotation,
				};
				
				nUI:TableInsertByValue( UnitPanelList, panel_item );
				
				-- create an anchor frame for the panel
				
				local pframe     =  panel or CreateFrame( "Frame", panel_name, nUI_UnitPanelSelector, "SecureStateHeaderTemplate" );
				local unit_panel =
				{
					name    = panel_name,
					options = panel_options,
					frame   = pframe,
				};
				
				pframe.Units = {};
				pframe:Hide();
				pframe:SetPoint( "CENTER", nUI_Dashboard, "CENTER", 0, 0 );
				
				nUI:TableInsertByValue( nUI.UnitPanels, unit_panel );

				-- register this panel with the selector
				
				nUI_UnitPanelSelector:SetAttribute( "addchild", pframe );
				pframe:SetAttribute( "showstates", panel_name );
				panel_config.selected = false;
		
				if panel_name == nUI_Options.unit_panel then
					have_selection = true;
				end
				
				-- script to enable and disabl the attached unit frames when the
				-- panel is shown or hidden... this way when we're using, for example,
				-- the 25 man raid unit panel, the 10 man raid, 15 man raid and the
				-- 40 man raid panel units are not trying to update their unit frames
				-- because they are disabled while the 25 man panel is enabled... this
				-- saves much on graphics engine and CPU load
				
				pframe:SetScript( "OnShow",
				
					function()

						if GameTooltip:IsOwned( nUI_UnitPanelSelector.button ) then
							GameTooltip:SetText( panel_config.desc or nUI_L["Click to change unit frame panels"] );
						end
						
						nUI_Options.unit_panel = panel_name;
						panel_config.selected = true;
				
						nUI_UnitPanelSelector.text:SetText( panel_config.label );
						nUI_UnitPanelSelector.desc = panel_config.desc;
						
						for name in pairs( pframe.Units ) do
							pframe.Units[name].setEnabled( true );
						end
					end
				);
				
				pframe:SetScript( "OnHide",
				
					function()
						
						panel_config.selected = false;
						
						for name in pairs( pframe.Units ) do
							pframe.Units[name].setEnabled( false );
						end
					end
				);
				
				-- spin the list of unit's in the panel and create as required
				
				for unit_name in pairs( panel_config.units ) do
				
					local config  = panel_config.units[unit_name];
					local options = config.options;
					local anchor  = config.anchor;
				
					-- if the unit is enabled, create it
					
					if options.enabled then
							
						local unit =
						{
							frame   = nUI_Unit:createUnit( unit_name, unit_panel.frame, options ),
							panel   = panel_name,
							name    = unit_name,
							options = options,
							anchor  = anchor,
						};
						
						unit.frame.setEnabled( false );
						pframe.Units[unit_name] = unit.frame;
						
						nUI:TableInsertByValue( nUI.UnitFrames, unit );
						
					end
				end			
			end
		end
		
		-- spin the list of all of the units we created and anchor them
		
		for i=1,#nUI.UnitFrames do
			nUI.UnitFrames[i].frame.applyAnchor( nUI.UnitFrames[i].anchor );
		end
		
		-- if we have no selected unit panels (first time loaded) then default to
		-- the solo player unit panel
		
		nUI_UnitPanelSelector:SetAttribute( "state", have_selection and nUI_Options.unit_panel or nUI_UNITPANEL_PLAYER );

		-- sort the list of panels by selector order then create a state
		-- rotation string for the selector button
		
		local state_string = "";
		
		table.sort( UnitPanelList, SortPanelList );
		
		for i=1,#UnitPanelList do
			state_string = state_string..(i==1 and "" or ",")..UnitPanelList[i].name;
		end
		
		nUI_UnitPanelSelector.button:SetAttribute( "newstate", state_string );
		
	end
end

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

local function onUnitPanelEvent()
	
	if event == "VARIABLES_LOADED" then

		nUI:registerSkinnedFrame( frame );
		nUI:registerScalableFrame( frame );
		
	end
end

nUI_UnitPanelSelector:SetScript( "OnEvent", onUnitPanelEvent );
nUI_UnitPanelSelector:RegisterEvent( "VARIABLES_LOADED" );
