class CompanionHealthStatListener extends ScriptStatPoolsListener
{
	private var m_healthbar : weak< CompanionHealthBarGameController >;

	public function BindHealthbar( bar : CompanionHealthBarGameController )
	{
		m_healthbar = bar;
	}

	public override function OnStatPoolValueChanged( oldValue : Float, newValue : Float, percToPoints : Float )
	{
		m_healthbar.UpdateHealthValue( newValue );
	}

}

class CompanionHealthBarGameController extends inkHUDGameController
{
	private editable var m_healthbar : inkWidgetRef;
	private var m_root : weak< inkWidget >;
	private var m_flatheadListener : CallbackHandle;
	private var m_isActive : Bool;
	private var m_maxHealth : Float;
	private var m_healthStatListener : CompanionHealthStatListener;
	private var m_companionBlackboard : weak< IBlackboard >;
	private var m_gameInstance : GameInstance;
	private var m_statPoolsSystem : StatPoolsSystem;

	protected event OnInitialize()
	{
		m_root = GetRootWidget();
		m_root.SetVisible( false );
		m_companionBlackboard = GetBlackboardSystem().Get( GetAllBlackboardDefs().UI_Companion );
		m_flatheadListener = m_companionBlackboard.RegisterDelayedListenerBool( GetAllBlackboardDefs().UI_Companion.flatHeadSpawned, this, 'OnFlatheadStatusChanged' );
		m_gameInstance = ( ( PlayerPuppet )( GetOwnerEntity() ) ).GetGame();
		m_statPoolsSystem = GameInstance.GetStatPoolsSystem( m_gameInstance );
		m_healthStatListener = new CompanionHealthStatListener;
		m_healthStatListener.BindHealthbar( this );
	}

	protected event OnFlatheadStatusChanged( value : Bool )
	{
		if( m_isActive != value )
		{
			m_isActive = value;
			if( m_isActive )
			{
				RegisterStatsListener();
				m_root.SetVisible( true );
			}
			else
			{
				m_root.SetVisible( false );
				UnregisterStatsListener();
			}
		}
	}

	private function RegisterStatsListener()
	{
		var flatheadPuppet : weak< ScriptedPuppet >;
		var flatheadEntityID : EntityID;
		flatheadPuppet = SubCharacterSystem.GetInstance( m_gameInstance ).GetFlathead();
		flatheadEntityID = flatheadPuppet.GetEntityID();
		m_statPoolsSystem.RequestRegisteringListener( flatheadEntityID, gamedataStatPoolType.Health, m_healthStatListener );
		m_maxHealth = m_statPoolsSystem.GetStatPoolMaxPointValue( flatheadEntityID, gamedataStatPoolType.Health );
	}

	private function UnregisterStatsListener()
	{
		var flatheadPuppet : weak< ScriptedPuppet >;
		var flatheadEntityID : EntityID;
		flatheadPuppet = SubCharacterSystem.GetInstance( m_gameInstance ).GetFlathead();
		flatheadEntityID = flatheadPuppet.GetEntityID();
		m_statPoolsSystem.RequestUnregisteringListener( flatheadEntityID, gamedataStatPoolType.Health, m_healthStatListener );
	}

	public function UpdateHealthValue( value : Float )
	{
		inkWidgetRef.SetScale( m_healthbar, Vector2( value / m_maxHealth, 1.0 ) );
	}

}

