-- Speical thanks to Shadowd and Kergoth for the sample code to find nameplates.

local TimeElapsed = 0;
SCT.UnitPlates = {};

----------------------
--See if its a valied nameplate health bar
local function FindHealthBar( ... ) 
    for i=1,select( '#', ... ) do 
        local healthBar = select( i, ... ); 
        if( healthBar and not healthBar.SCTHooked and healthBar.GetFrameType and healthBar:GetFrameType() == "StatusBar" and not healthBar:GetName() and healthBar:IsVisible() ) then 
            return healthBar; 
        end 
    end 
end 
 
----------------------
--Find any on hooked health bars.
local function UpdateFrames( ... ) 
    for i=1, select( '#', ... ) do 
        local healthBar = FindHealthBar( select( i, ... ):GetChildren() ); 
        if( healthBar ) then 
          SCT:HookScript(healthBar, "OnHide");
          SCT:HookScript(healthBar, "OnShow");
          SCT:HookScript(healthBar, "OnValueChanged");
					healthBar.SCTHooked = true;
        end 
    end 
end 

----------------------
--Create frame to trigger health bars
function SCT:CreateUnitUpdate()
	if (not SCT.UnitPos) then
		SCT.UnitPos = CreateFrame("Frame", "SCT_UnitPos",UIParent);
		SCT.UnitPos:SetScript("OnUpdate", SCT.UnitOnUpdate);
	end
end

----------------------
--Look for new health bars .25 seconds
function SCT:UnitOnUpdate( elapsed ) 
    TimeElapsed = TimeElapsed + elapsed; 
    if( TimeElapsed > 0.25 ) then 
      TimeElapsed = 0; 
      UpdateFrames( WorldFrame:GetChildren() ); 
    end 
end 

----------------------
--When a health bar is shown, get the name and run any hooks
function SCT:OnShow()
	local name = select( 5, this:GetParent():GetRegions() ):GetText();
	if (not SCT.UnitPlates[name]) and (this:IsVisible()) then
		SCT.UnitPlates[name] = this;
	end
	self.hooks[this].OnShow();
end

----------------------
--When a health bar value changes, get the name and run any hooks
--This catches more bars when they are coming in and and out of view, etc...
function SCT:OnValueChanged()
	local name = select( 5, this:GetParent():GetRegions() ):GetText();
	if (not SCT.UnitPlates[name]) and (this:IsVisible()) then
		SCT.UnitPlates[name] = this;
	end
	self.hooks[this].OnValueChanged();
end

----------------------
--When a new health bar is hidden, remove the name and run any hooks
function SCT:OnHide()
	local name = select( 5, this:GetParent():GetRegions() ):GetText();
	SCT.UnitPlates[name] = nil;
	self.hooks[this].OnHide();
end

----------------------
--Get namplate if there is one
function SCT:GetNameplate(target)
	local parent
	if self.UnitPlates[target] then
		parent = self.UnitPlates[target];
	end
	return parent;
end

----------------------
--Start Nameplate tracking
function SCT:EnableNameplate()
	self:CreateUnitUpdate();
	ShowFriendNameplates();
end

----------------------
--Start Nameplate tracking
function SCT:DisableNameplate()
	HideFriendNameplates();
end