using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace Sockeye.Util
{

    /// <summary>
    /// what it says
    /// </summary>
    public static class RetryHelper
    {
       
        /// <summary>
        /// 
        /// </summary>
        /// <param name="times"></param>
        /// <param name="delay"></param>
        /// <param name="log"></param>
        /// <param name="logPrepend"></param>
        /// <param name="operation"></param>
        public static void RetryOnException(int times, TimeSpan delay, ILogger log, string logPrepend, Action operation)
        {
            var attempts = 0;
            do
            {
                try
                {
                    attempts++;
                    operation();
                    break; // Sucess! Lets exit the loop!
                }
                catch (Exception ex)
                {
                    if (attempts == times)
                        throw;
                    
                    log.LogError(ex, $"{logPrepend} Exception caught on attempt {attempts} of {times} - will retry after delay {delay}");                  

                    Task.Delay(delay).Wait();
                }
            } while (true);
        }







    }
}