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

namespace bbiwarg.Utility
{
    class Timer
    {
        private static Dictionary<String, Stopwatch> stopwatches = new Dictionary<string, Stopwatch>();
        private static Dictionary<String, double> minTimes = new Dictionary<string, double>();
        private static Dictionary<String, double> maxTimes = new Dictionary<string, double>();
        private static Dictionary<String, double> sumTimes = new Dictionary<string, double>();
        private static Dictionary<String, int> numTimes = new Dictionary<string, int>();

        public static void start(String name) {
            if (!stopwatches.ContainsKey(name))
            {
                stopwatches.Add(name, new Stopwatch());
                minTimes.Add(name, int.MaxValue);
                maxTimes.Add(name, 0);
                sumTimes.Add(name, 0);
                numTimes.Add(name, 0);
            }
            stopwatches[name].Restart();
        }

        public static void stop(String name) {
            stopwatches[name].Stop();
            double time = Math.Round((double)stopwatches[name].ElapsedTicks / (double)Stopwatch.Frequency * 1000.0, 2);
            if (time < minTimes[name]) minTimes[name] = time;
            if (time > maxTimes[name]) maxTimes[name] = time;
            sumTimes[name] += time;
            numTimes[name]++;
        }

        public static void output(String name) {
            Console.WriteLine("name:{0}\tavg:{1:00.00}\tmin:{2:00.00}\tmax:{3:00.00}", name, sumTimes[name] / Math.Max(numTimes[name], 1), minTimes[name], maxTimes[name]);
       }

        public static void outputAll() {
            Console.WriteLine("---TIMERS-START---");
            foreach (String name in stopwatches.Keys) {
                output(name);
            }
            Console.WriteLine("---TIMERS-END---");
        }

    }
}
