using System;
using System.Collections.Generic;
using System.Linq;

namespace SWRIS.Models
{
    public  class SpeedVariationModel
    {
        private const int SampleSize = 5;
        private readonly Queue<double> RecentSpeeds = new Queue<double>();
        private double VariationThreshold { get; set; } = 0.25;
        public bool IsSpeedStable { get; private set; } = false;
        private double CurrentVariation { get; set; }

        public event EventHandler<bool> SpeedStableChanged;
        public SpeedVariationModel(double variationThreshold)
        {
            VariationThreshold = variationThreshold;
        }
        public void AddSpeedData(double speed)
        {
            // 更新数据窗口
            RecentSpeeds.Enqueue(speed);
            if (RecentSpeeds.Count > SampleSize)
                RecentSpeeds.Dequeue();

            bool _isStable = CheckStability();
            if (IsSpeedStable != _isStable)
            {
                IsSpeedStable = _isStable;
                SpeedStableChanged?.Invoke(this, IsSpeedStable);
            }
        }

        private bool CheckStability()
        {
            if (RecentSpeeds.Count < 2)
            {
                return false;
            }
            double currentSpeed = RecentSpeeds.Last();
            double avgSpeed = RecentSpeeds.Average();
            // 计算当前速度相对于平均值的偏差
            CurrentVariation = Math.Abs(currentSpeed - avgSpeed) / avgSpeed;
            return CurrentVariation <= VariationThreshold;
        }

        // 重置状态
        public void Reset()
        {
            RecentSpeeds.Clear();
            IsSpeedStable = false;
            CurrentVariation = 0;
        }
    }
}
