class EntityHealthStatListener extends ScriptStatPoolsListener
{
	private var m_healthbar : weak< EntityHealthBarGameController >;

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

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

}

class EntityHealthBarGameController extends inkGameController
{
	private editable var m_healthControllerRef : inkWidgetRef;
	private editable var m_healthPercentageRef : inkTextRef;
	private editable var m_targetEntityRef : EntityReference;
	private var m_healthStatListener : EntityHealthStatListener;
	private var m_healthController : weak< NameplateBarLogicController >;
	private var m_gameInstance : GameInstance;
	private var m_targetEntityID : EntityID;

	protected event OnInitialize()
	{
		m_gameInstance = ( ( PlayerPuppet )( GetOwnerEntity() ) ).GetGame();
		m_healthController = ( ( NameplateBarLogicController )( inkWidgetRef.GetController( m_healthControllerRef ) ) );
		RegisterHealthStatListener();
	}

	protected event OnUninitialize()
	{
		GameInstance.GetStatPoolsSystem( m_gameInstance ).RequestUnregisteringListener( m_targetEntityID, gamedataStatPoolType.Health, m_healthStatListener );
	}

	private function RegisterHealthStatListener()
	{
		var entityIds : array< EntityID >;
		m_healthStatListener = new EntityHealthStatListener;
		m_healthStatListener.BindHealthbar( this );
		GetFixedEntityIdsFromEntityReference( m_targetEntityRef, m_gameInstance, entityIds );
		m_targetEntityID = entityIds[ 0 ];
		GameInstance.GetStatPoolsSystem( m_gameInstance ).RequestRegisteringListener( m_targetEntityID, gamedataStatPoolType.Health, m_healthStatListener );
	}

	public function UpdateHealthValue( newValue : Float )
	{
		m_healthController.SetNameplateBarProgress( newValue / 100.0, false );
		inkTextRef.SetText( m_healthPercentageRef, IntToString( ( ( Int32 )( newValue ) ) ) );
	}

	protected event OnUpdateEntityHealthListenersEvent( evt : questUpdateEntityHealthListenersEvent )
	{
		if( m_targetEntityRef == evt.entityRef )
		{
			GameInstance.GetStatPoolsSystem( m_gameInstance ).RequestUnregisteringListener( m_targetEntityID, gamedataStatPoolType.Health, m_healthStatListener );
			RegisterHealthStatListener();
		}
	}

}

import class questUpdateEntityHealthListenersEvent extends Event
{
	import var entityRef : EntityReference;
}

