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

namespace MECF.Framework.Common.SicMath
{

    public class TimeDomainArithmeticMeanFilter : IFilter
    {

        #region Variables

        private readonly List<(DateTime time, double value)> _rawDataBuffer;

        #endregion

        #region Constructors

        public TimeDomainArithmeticMeanFilter(double durationSec)
        {
            FilterDurationInSec = durationSec;
            _rawDataBuffer = new List<(DateTime, double)>();
        }

        #endregion

        #region Properties

        /// <summary>
        /// 返回滤波时间。
        /// </summary>
        public double FilterDurationInSec { get; set; }

        #endregion

        #region Methods

        public void Feed(double value)
        {
            var now = DateTime.Now;
            _rawDataBuffer.Add((now, value));
            _rawDataBuffer.RemoveAll(x => x.time < now.AddSeconds(-FilterDurationInSec));
        }


        public double Filter()
        {
            // 如果采样时间设定值小于0,直接返回最后一个采样点数值。
            if (FilterDurationInSec <= 0)
                return _rawDataBuffer.Last().value;

            // 如果没有采样数据，返回double.NaN
            if (_rawDataBuffer.Count <= 0)
                return double.NaN;

            // 返回采样点的算术平均值。
            return _rawDataBuffer
                .Where(x=>double.IsNaN(x.value) == false)
                .Select(x => x.value)
                .Average();
        }

        #endregion
        
    }
}