using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;

namespace Betfair.Gamex.API
{
    /// <summary>
    /// Logs time taken on server
    /// </summary>
    public class PerformanceTimer
    {
        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceFrequency(out long lpFrequency);

        private long m_StartTime;
        private long m_StopTime;
        private long m_Frequency;

        /// <summary>
        /// Constructor
        /// </summary>
        public PerformanceTimer()
        {
            if (QueryPerformanceFrequency(out m_Frequency) == false)
            {
                // high-performance counter not supported
                throw new Win32Exception();
            }
        }

        /// <summary>
        /// Start timing
        /// </summary>
        public void Start()
        {
            m_StartTime = 0;
            m_StopTime = 0;
            QueryPerformanceCounter(out m_StartTime);
        }

        /// <summary>
        /// Stop timing
        /// </summary>
        public void Stop()
        {
            QueryPerformanceCounter(out m_StopTime);
        }

        /// <summary>
        /// Duration in seconds
        /// </summary>
        public decimal Duration
        {
            get
            {
                decimal start = Convert.ToDecimal(m_StartTime);
                decimal stop = Convert.ToDecimal(m_StopTime);
                decimal freq = Convert.ToDecimal(m_Frequency);

                return (stop - start) / freq;
            }
        }

        /// <summary>
        /// Duration in milliseconds
        /// </summary>
        public int MillisecondDuration
        {
            get
            {
                return Convert.ToInt32(this.Duration * 1000);
            }
        }

        /// <summary>
        /// Start time
        /// </summary>
        public decimal StartTime
        {
            get
            {
                decimal start = Convert.ToDecimal(m_StartTime);
                decimal freq = Convert.ToDecimal(m_Frequency);

                return (start / freq); 
            }
        }

        /// <summary>
        /// Stop time
        /// </summary>
        public decimal StopTime
        {
            get 
            {
                decimal stop = Convert.ToDecimal(m_StopTime);
                decimal freq = Convert.ToDecimal(m_Frequency);

                return (stop / freq); 
            }
        }
    }
}
