namespace Syntriax.Engine.Systems.Time;

public class TickerBehaviour : StopwatchBehaviour, ITicker
{
    public event ITicker.TickerTickEventHandler? OnTick = null;

    public double Period { get; set; } = 1f;
    public int TickCounter { get; private set; } = 0;

    private double nextTick = 0f;

    public override void Start()
    {
        TickCounter = 0;
        base.Start();
        nextTick = Time + Period;
    }

    protected override void OnUpdate()
    {
        base.OnUpdate();

        while (Time > nextTick)
        {
            nextTick += Period;
            TickCounter++;
            OnTick?.Invoke(this);
        }
    }

    protected override void OnFinalize()
    {
        base.OnFinalize();

        TickCounter = 0;
        nextTick = 0f;
    }
}