using System;
using System.Collections.Specialized;

namespace VlnProfiler
{
	/// <summary>
	/// Summary description for Profiler.
	/// </summary>
	public class Profiler
	{
		static HybridDictionary dicTiming;
		static HybridDictionary dicDuration;

		static Profiler()
		{
			Reset();
		}

		public static void Reset()
		{
			dicTiming = new HybridDictionary();
			dicTiming["  Total"]=DateTime.Now;
			dicDuration = new HybridDictionary();
		}

		public static void Start(string sName)
		{
			dicTiming[sName]=DateTime.Now;
		}

		public static void End(string sName)
		{
			if( dicDuration.Contains(sName))
				dicDuration[sName]=((TimeSpan) dicDuration[sName]) + (DateTime.Now - ((DateTime) dicTiming[sName]));
			else
				dicDuration[sName]=DateTime.Now - ((DateTime) dicTiming[sName]);
		}

		public static string ToString(string Format)
		{
			string str="";
			string sep="";
			if(Format.IndexOf("%")>=0)
			{
				double ttl = Convert.ToDouble(((TimeSpan) (DateTime.Now - ((DateTime) dicTiming["  Total"]))).Ticks);
				double ttlOther=ttl;
				foreach(string strKey in dicDuration.Keys)
				{
					ttlOther-=((TimeSpan) dicDuration[strKey]).Ticks;
					double dt = Convert.ToDouble(((TimeSpan) dicDuration[strKey]).Ticks)/ttl;
					//TODO: If Percent - Convert to Percent of Total
					str+=sep+dt.ToString(Format) + " " + strKey;
					sep="\r\n";
				}
				ttlOther = ttlOther/ttl;
				str+=sep+ttlOther.ToString(Format) + " Other";
			}
			else
			{
				foreach(string strKey in dicDuration.Keys)
				{
					str+=sep+((TimeSpan)dicDuration[strKey]).ToString(/*Format*/) + " " + strKey;
					sep="\r\n";
				}
			}
			str+=sep + "".PadRight(20,'-');
			str+=sep + ((TimeSpan) (DateTime.Now - ((DateTime) dicTiming["  Total"]))).ToString(/*Format*/) + " Total";
			return str;
		}
	}
}
