namespace Engine.Util;

public class TickableTimer
{
  public event Action? OnFinished;
  public event Action<double>? OnUpdate;

  public double TotalTime
  {
    get => _totalTime;
    set
    {
      if (value <= 0)
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value);

      _totalTime = value;
      CurrentTime = value;
    }
  }

  public double CurrentTime
  {
    get => _currentTime;
    set
    {
      if (value < 0)
        value = 0;
      if (value > TotalTime)
        value = TotalTime;

      _currentTime = value;
      OnUpdate?.Invoke(value);

      if (IsFinished)
        OnFinished?.Invoke();
    }
  }

  public bool IsFinished => _currentTime <= 0;

  private double _totalTime;
  private double _currentTime;

  public TickableTimer(double parTotalTime)
  {
    if (parTotalTime <= 0)
      ArgumentOutOfRangeException.ThrowIfNegativeOrZero(parTotalTime);

    _totalTime = parTotalTime;
    _currentTime = parTotalTime;
  }

  public void Update(double parDeltaTime)
  {
    CurrentTime -= parDeltaTime;
  }

  public void Reset()
  {
    CurrentTime = TotalTime;
  }
}