using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;


namespace StarTrinity
{

	[System.Runtime.InteropServices.ComVisible(false)]
    public class DelayCounter
    {
        [DllImport("kernel32.dll")]
        extern static short QueryPerformanceCounter(ref long x);
        [DllImport("kernel32.dll")]
        extern static short QueryPerformanceFrequency(ref long x);

        private long _startValue = 0;
        private long _endValue = 0;
        private long _freq = 0;

        private string _module = "";
        private string _objectName = "";
        
        public bool DoWriteLogs { get; set; }


        /// <summary>
        /// starts delay calculation
        /// </summary>
        public DelayCounter(string module = "", string objectName = "")
        {            
            _module = module;
            _objectName = objectName;
            QueryPerformanceCounter(ref _startValue);
        }
                
        /// <summary>
        /// measures delay since constructor was called
        /// </summary>
        /// <returns>delay in seconds</returns>
        public double End()
        {
            double result = 0;
            try
            {
                QueryPerformanceCounter(ref _endValue);
                QueryPerformanceFrequency(ref _freq);
                                
                result = (_endValue - _startValue) * 1.0 / _freq;
            }
            catch (Exception ex)
            {
            
            }

            return result;            
        }

        public double End(string objectName, string actionName, Log log, double logThresholdMs = 1, double warningThresholdMs = 100)
        {
            double result = 0;
            try
            {
                QueryPerformanceCounter(ref _endValue);
                QueryPerformanceFrequency(ref _freq);

                result = (_endValue - _startValue) * 1.0 / _freq;

                if (result * 1000 > logThresholdMs)
                    log.Write("DelayCounter", objectName, actionName + ": Delay (" + (result * 1000).ToString() + " ms.) is more than " + logThresholdMs.ToString() + " ms.");
                else if (result * 1000 > warningThresholdMs)
                    log.WriteWarning("DelayCounter", objectName, actionName + ": Delay (" + (result * 1000).ToString() + " ms.) is more than " + warningThresholdMs.ToString() + " ms");
				
            }
            catch (Exception ex)
            {
                log.WriteException("DelayCounter", ex, actionName + ": " + ex.Message);
            }
            return result;
        }

    }
}
