using Engine.Scene;
using Engine.Util;

namespace DoomDeathmatch.Script;

public class AnimationPlayer<T>(float parInterval) : IUpdate
{
  public List<T> Frames { get; init; } = [];
  public bool IsPlaying { get; private set; } = false;
  public int NextFrame { get; private set; } = 0;

  public event Action<T>? OnFrameChanged;
  public event Action? OnFinish;

  private readonly TickableTimer _timer = new(parInterval);

  public void Start()
  {
    Reset();
    IsPlaying = true;
  }

  public void Update(double parDeltaTime)
  {
    if (!IsPlaying)
      return;

    _timer.Update(parDeltaTime);

    if (_timer.CurrentTime < _timer.TotalTime * (1.0f - 1.0f / Frames.Count * NextFrame))
    {
      OnFrameChanged?.Invoke(Frames[NextFrame]);
      NextFrame++;
    }

    if (_timer.IsFinished)
    {
      OnFinish?.Invoke();

      Reset();
    }
  }

  public void Reset()
  {
    _timer.Reset();
    NextFrame = 0;
    IsPlaying = false;
  }
}