using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CrazyStudio.Core.Common.Status
{
    public class FPSCounter : IDisposable
    {
        private readonly Stopwatch _stopwatch = new Stopwatch();
        private readonly Queue<double> _frameTimes = new Queue<double>();
        private readonly int _sampleCount = 60; // 采样帧数（窗口大小）
        private double _currentFPS;

        public FPSCounter()
        {
            _stopwatch.Start();
            _currentFPS = 0;
        }

        public void Update()
        {
            // 记录当前帧时间
            double frameTime = _stopwatch.Elapsed.TotalSeconds;
            _stopwatch.Restart();

            // 维护时间队列
            _frameTimes.Enqueue(frameTime);
            if (_frameTimes.Count > _sampleCount)
            {
                _frameTimes.Dequeue();
            }

            // 计算平均帧时间
            double averageFrameTime = 0;
            foreach (var time in _frameTimes)
            {
                averageFrameTime += time;
            }
            averageFrameTime /= _frameTimes.Count;

            // 计算FPS（避免除零）
            _currentFPS = averageFrameTime > 0 ? 1 / averageFrameTime : 0;
        }

        public double CurrentFPS => _currentFPS;

        public void Dispose()
        {
            _stopwatch.Stop();
        }
    }
}
