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

namespace BulletTest
{
    class Profiler : IProfiler
    {
        Stopwatch frameWatch = new Stopwatch();
        long totalTicks = 0;
        long count = 0;
        struct Profile
        {
            public string Name;
            public Stopwatch ProfileWatch;
        }
        Stack<Profile> Profiles = new Stack<Profile>();
        class Profile2
        {
            public long ms;
            public long count;
        }
        Dictionary<string, Profile2> Times = new Dictionary<string, Profile2>();
        #region IProfiler メンバ

        public void StartProfile(string profile)
        {
            Profiles.Push(new Profile { Name = profile, ProfileWatch = Stopwatch.StartNew() });
        }

        public void EndProfile(string profile)
        {
            Profile data = Profiles.Pop();
            if (data.Name != profile)
                throw new Exception();
            if (Times.ContainsKey(data.Name))
            {
                Times[data.Name].count++;
                Times[data.Name].ms += data.ProfileWatch.ElapsedTicks / (Stopwatch.Frequency / 1000);
            }
            else
            {
                Times.Add(data.Name, new Profile2 { ms = data.ProfileWatch.ElapsedTicks / (Stopwatch.Frequency / 1000), count = 1 });
            }
        }

        public void BeginProfileFrame()
        {
            frameWatch.Reset();
            frameWatch.Start();
        }

        public void EndProfileFrame()
        {
            totalTicks += frameWatch.ElapsedTicks;
            ++count;
            if (count >= 60)
            {
                Console.WriteLine("FPS=" + Convert.ToString(totalTicks / count / (Stopwatch.Frequency / 1000)) + "ms");
                totalTicks = 0;
                count = 0;
                foreach (var i in Times)
                {
                    Console.WriteLine(i.Key + "=" + Convert.ToString(i.Value.ms / i.Value.count));
                }
                Times.Clear();
            }
        }

        #endregion
    }
}
