namespace MinicsConsole.Helper;

public class DailyRoutinHelper(ILog log) : IDisposable
{
    private Timer? _timer;
    private readonly ConcurrentDictionary<string, Func<bool>> _routines = [];

    public bool AddorUpdateRoutinWork(string name, Func<bool> action)
    {
        if (string.IsNullOrEmpty(name) || action is null)
            return false;

        _routines[name] = action;
        return true;
    }

    public bool StartService(TimeSpan routinTime)
    {
        this._timer = new(TimerCallback, null, routinTime, routinTime);

        return true;
    }
    void TimerCallback(object? state)
    {
        Parallel.ForEach(this._routines, routine =>
        {
            try
            {
                if (routine.Value?.Invoke() is not true)
                {
                    log.Warning($"Routine Work {routine.Key} Rejected or not success");
                }
            }
            catch
            {
                log.Error($"Routine Work {routine.Key} Error");
            }
        });
    }


    public void Dispose()
    {
        this._timer?.Dispose();
        this._routines.Clear();
    }
}
