using System;
using System.Linq;
using System.Threading;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Log;

namespace Siger.ApiDashboard.Tasks
{
    public class CnSummaryHelper : IDisposable
    {
        private static CnSummaryHelper _helper;
        public static CnSummaryHelper Instance = _helper ?? (_helper = new CnSummaryHelper());

        public void StartTask()
        {
            Logger.RegisterLogEngine(Module.Dashboard);
            try
            {
                var thread = new Thread(Process)
                {
                    IsBackground = true
                };
                thread.Start();
            }
            catch (Exception e)
            {
                Logger.WriteLineError("Cn Summary failed, error:" + e);
            }
        }

        private void Process()
        {
            while (true)
            {
                //一天汇总一次
                if (DateTime.Now.Hour == 0 && DateTime.Now.Minute < 10)
                {
                    Execute();
                }
                Thread.Sleep(1000 * 60 * 5); // 5分钟
            }
        }

        private void Execute()
        {
            DbHelper.Instance.AsyncData();
        }

        public void Dispose()
        {
            DbHelper.Instance?.Dispose();
        }
    }
}
