using DoomDeathmatch.Script.Model;

namespace DoomDeathmatch.Component.MVC.Health;

public class HealthController : Engine.Scene.Component.Component
{
  public event Action? OnDeath;
  public bool IsAlive => _healthModel.Health > 0;

  private readonly HealthModel _healthModel;
  private HealthView? _healthView;

  public HealthController(float parHealth = 100)
  {
    _healthModel = new HealthModel(parHealth);
  }

  public override void Awake()
  {
    _healthModel.HealthChanged += OnHealthChanged;
    _healthView = GameObject.GetComponent<HealthView>();

    if (_healthView != null)
    {
      _healthView.UpdateView(_healthModel);
      _healthModel.HealthChanged += _healthView.UpdateView;
    }
  }

  public void SetMaxHealth(float parMaxHealth)
  {
    _healthModel.MaxHealth = parMaxHealth;
    _healthModel.Health = parMaxHealth;
  }

  public void TakeDamage(float parDamage)
  {
    _healthModel.Health -= parDamage;
  }

  public void Heal(float parHeal)
  {
    _healthModel.Health += parHeal;
  }

  private void OnHealthChanged(HealthModel parHealthModel)
  {
    if (!IsAlive)
    {
      OnDeath?.Invoke();
    }
  }
}