using JLHHJSvr.LJException;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;

namespace JLHHJSvr.Tools
{
    public class ScheduledTimeTask
    {
        public string Name { get; }
        public TimeSpan RunAt { get; }
        public Action TaskAction { get; }
        private Timer _timer;

        public ScheduledTimeTask(string name, TimeSpan runAt, Action action)
        {
            Name = name;
            RunAt = runAt;
            TaskAction = action;
            ScheduleNext();
        }

        private void ScheduleNext()
        {
            var now = DateTime.Now;
            var nextRun = DateTime.Today.Add(RunAt);
            // 下一天执行
            if (now > nextRun) nextRun = nextRun.AddDays(1);
            var timeToGo = nextRun - now;
            _timer = new Timer(_ =>
            {
                Trace.Write($"{Name}定时任务执行!!!");
                TaskAction.Invoke();
                ScheduleNext(); // 再次调度
            }, null, timeToGo, Timeout.InfiniteTimeSpan);
        }

        public void Stop() => _timer?.Dispose();
    }

    public class DailySchedulerManager
    {
        private readonly Dictionary<string, ScheduledTimeTask> _tasks = new Dictionary<string, ScheduledTimeTask>();

        public void AddTask(string name, TimeSpan runAt, Action action)
        {
            if (_tasks.ContainsKey(name)) throw new LJCommonException($"任务 \"{name}\" 已存在");
            _tasks[name] = new ScheduledTimeTask(name, runAt, action);
        }

        public void RemoveTask(string name)
        {
            if (_tasks.TryGetValue(name, out var task))
            {
                task.Stop();
                _tasks.Remove(name);
            }
        }

        public void StopAll()
        {
            foreach (var task in _tasks.Values) task.Stop();
            _tasks.Clear();
        }
    }

}
