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

namespace FLY.OBJComponents.Server
{
    /// <summary>
    /// 周期保存数据,写入到数据库的周期为20s; 
    /// 但数据的周期最小为1s
    /// </summary>
    public class PeriodicallySaveData<T>
    {
        Stopwatch stopwatch_interval = new Stopwatch();
        Stopwatch stopwatch_1min = new Stopwatch();
        List<T> dbWidths_1min = new List<T>();
        /// <summary>
        /// 数据保存周期，单位s
        /// </summary>
        public int IntervalSec = 5;
        /// <summary>
        /// 把缓存区的数据一次性导出
        /// </summary>
        public Action<List<T>> SaveList;
        /// <summary>
        /// 创造一次数据
        /// </summary>
        public Func<T> CreateData;

        public void Init(int intervalSec, Action<List<T>> saveList, Func<T> createData)
        {
            IntervalSec = intervalSec;
            SaveList = saveList;
            CreateData = createData;
            FObjBase.PollModule.Current.Poll_Config(
                FObjBase.PollModule.POLL_CONFIG.ADD, OnPoll, TimeSpan.FromSeconds(1));
        }
        void OnPoll()
        {
            if (stopwatch_1min.IsRunning && stopwatch_1min.Elapsed >= TimeSpan.FromSeconds(20))
            {
                //启动了1min 且到点了
                if (dbWidths_1min.Count > 0)
                {
                    SaveList(dbWidths_1min);
                    dbWidths_1min.Clear();
                    stopwatch_1min.Restart();
                }
                else
                {
                    stopwatch_1min.Reset();
                }
            }

            if (!stopwatch_interval.IsRunning)
            {
                stopwatch_interval.Start();
                return;
            }
            else
            {
                if (stopwatch_interval.Elapsed < TimeSpan.FromSeconds(IntervalSec))
                    return;
                else
                    stopwatch_interval.Restart();
            }

            //记录数据
            T db_Width = CreateData();
            if (db_Width == null)
            {
                //没有，退出
                return;
            }

            //写入数据库
            if (!stopwatch_1min.IsRunning)
            {
                //第1次立刻写入
                SaveList(new List<T> { db_Width });
                stopwatch_1min.Start();
            }
            else
            {
                //第2次，1分钟后才能保存
                dbWidths_1min.Add(db_Width);
            }
        }
    }
}
