using DoomDeathmatch.Component.MVC.Model;
using DoomDeathmatch.Component.MVC.View;

namespace DoomDeathmatch.Component.MVC.Controller;

public class HealthController : Engine.Scene.Component.Component
{
  public event Action? OnDeath;

  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 (parHealthModel.Health <= 0)
    {
      OnDeath?.Invoke();
    }
  }
}