using Godot;

namespace Newlon.Components;

public partial class EntityHPObserver : Node
{
	[Export] private float _threshold = 0.5f;
	[Export] private bool _setGreater = false;
	[Export] private Entity _observedEntity;
	[Signal] public delegate void ThresholdReachedEventHandler();

	public override void _Ready()
	{
		_observedEntity.OnHPChanged += OnHPChanged;
	}

	private void OnHPChanged(float delta, Node origin)
	{
		if (_setGreater == false && _observedEntity.HP / _observedEntity.MaxHP < _threshold)
		{
			EmitSignal(SignalName.ThresholdReached);
			_observedEntity.OnHPChanged -= OnHPChanged;
			QueueFree();
		}
		else if (_setGreater && _observedEntity.HP / _observedEntity.MaxHP > _threshold)
		{
			EmitSignal(SignalName.ThresholdReached);
			_observedEntity.OnHPChanged -= OnHPChanged;
			QueueFree();
		}
	}
}
