using System;

using Polly;

// https://github.com/App-vNext/Polly

namespace TopNugetPackages
{
    public class MainPollyDriver
    {
        private static int times_exec = 0;
        private int MAX_TRIES = 3;
        private int MAX_WAIT_SEC = 2;

        private bool OnHandleFunc()
        {
            times_exec++;

            if (times_exec > MAX_TRIES)
                return true;

            throw new NotImplementedException();
        }

        // Fault-handling library that allows retry, circuit break, timeout, etc.
        // Good for repeating methods that have high chance of failure, such as DB connection,
        // http reads, other networking or file based processing.
        public void DoIt()
        {
            var ret = Policy
                        .Handle<NotImplementedException>()
                        .WaitAndRetry(new[] {
                            // retry 3 times after x seconds
                            TimeSpan.FromSeconds(MAX_WAIT_SEC),
                            TimeSpan.FromSeconds(MAX_WAIT_SEC),
                            TimeSpan.FromSeconds(MAX_WAIT_SEC)
                        }, (exception, timeSpan, retryCount, context) => {

                            var dt = DateTime.Now;
                            Console.WriteLine($"{dt} [{retryCount}] : {exception.Message}");
                        })
                        .Execute(OnHandleFunc);

            if (ret == true)
            {
                Console.WriteLine($"Success after {MAX_TRIES} tries!");
            }
        }
    }
}