using Godot;

namespace BITKit;

/// <summary>
/// 固定间隔工具，用于控制执行速率
/// </summary>
[System.Serializable]
public class IntervalTimer
{
    public IntervalTimer()
    {
        
    }
    /// <summary>
    /// 在构造函数中声明间隔时间
    /// </summary>
    /// <param name="interval"></param>
    public IntervalTimer(ulong interval)
    {
        this.interval = interval;
    }
    /// <summary>
    /// 间隔时间
    /// </summary>
    private readonly ulong interval;
    /// <summary>
    /// 可以执行的事件
    /// </summary>
    private ulong allowTime;
    /// <summary>
    /// 是否可以执行(执行重置间隔)
    /// </summary>
    public bool Allow
    {
        get
        {
            if (allowTime >= Time.GetTicksMsec()) return false;
            Release();
            return true;
        }
    }
    /// <summary>
    /// 是否可以执行(不会执行重置间隔)
    /// </summary>
    public bool AllowWithoutRelease => allowTime >= Time.GetTicksMsec();
    /// <summary>
    /// 重置执行间隔
    /// </summary>
    /// <param name="immediately">是否可以立即执行</param>
    public void Release(bool immediately=false)
    {
        var currentTime = Time.GetTicksMsec();
        allowTime = immediately ? currentTime : currentTime + interval*1000;
    }
}