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

namespace bbiwarg.Utility
{
    class Timer
    {
        private static Object sync = new object();
        private static Dictionary<String, Stopwatch> stopwatches = new Dictionary<string, Stopwatch>();
        private static Dictionary<String, double> currentTimes = new Dictionary<string, double>();
        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>();
        private static int maxNameLength = 1;

        public static void start(String name)
        {
            lock (sync)
            {
                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);
                    currentTimes.Add(name, 0);
                    maxNameLength = Math.Max(maxNameLength, name.Length);
                }
                stopwatches[name].Restart();
            }
        }

        public static void stop(String name)
        {
            lock (sync)
            {
                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]++;
                currentTimes[name] = time;
            }
        }
        public static void outputAll()
        {
            lock (sync)
            {
                StringBuilder divider = new StringBuilder();
                divider.Append("├-");
                divider.Append(new String('-', maxNameLength));
                divider.Append("-┼-------┼-------┤");

                Console.Clear();
                Console.WriteLine(String.Format("| {0,-" + maxNameLength + "} | {1,-5} | {2,-5} |", "NAME", "AVG.", "CUR."));
                Console.WriteLine(divider.ToString());
                foreach (String name in stopwatches.Keys)
                {
                    double average = sumTimes[name] / Math.Max(numTimes[name], 1);
                    double current = currentTimes[name];

                    Console.WriteLine(String.Format("| {0,-" + maxNameLength + "} | {1:00.00} | {2:00.00} |", name, average, current));
                }
            }
        }

    }
}
