using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CsvCount_ES
{
    public class PerformanceUtility
    {
        public static readonly TimeSpan DefaultTriggerTimeSpan = TimeSpan.FromMinutes(5);

        public static readonly TimeSpan DefaultIntervalTimeSpan = TimeSpan.FromMinutes(2);

        public static T OperationTimedMonitor<T>(TimeSpan trigger, TimeSpan interval, String message, Func<T> operation)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            Task<T> task = Task.Run<T>(operation);
            Task waitForTrigger = Task.Delay(trigger);

            Task.WaitAny(task, waitForTrigger);

            if (task.IsCompleted)
            {
                return task.Result;
            }
            else
            {
                String guid = Guid.NewGuid().ToString();
                LogService.WriteWarn(String.Format("Operation {0} timeout triggered, Message {1}, Time elasped {2}", guid, message, watch.ElapsedMilliseconds));

                Task waitInterval = Task.Delay(interval);
                Task.WaitAny(task, waitInterval);

                while (!task.IsCompleted)
                {
                    LogService.WriteWarn(String.Format("Operation {0} interval triggered, Time elasped {1}", guid, watch.ElapsedMilliseconds));
                    waitInterval = Task.Delay(interval);
                    Task.WaitAny(task, waitInterval);
                }

                return task.Result;
            }
        }
    }
}
