using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Windows.Forms;

namespace MTK
{
    public unsafe class WinIOLib
    {
        [DllImport("kernel32.dll")]
        extern static short QueryPerformanceCounter(ref long x);

        [DllImport("kernel32.dll")]
        extern static short QueryPerformanceFrequency(ref long x);

        static double _baseCnt = 0;
        static long _cpuCnt = 0;
        static long _dlyCnt = 0;
        public static int _dftI2CDlyTime = 10;
        public static void Delaytime(long dtime)
        {
            int tick = Environment.TickCount;
            while (Environment.TickCount - tick < dtime)
            {
                System.Windows.Forms.Application.DoEvents();
            }
        }
        public static void DelayUs(int us = -1)
        {
            if (us == -1)
                us = _dftI2CDlyTime;

            if (us == 0)
                return;

            if (_baseCnt == 0)
            {
                long cpuFreq = 0;
                QueryPerformanceFrequency(ref cpuFreq);
                _baseCnt = (cpuFreq) / 1000000;
            }

            QueryPerformanceCounter(ref _cpuCnt);
            _dlyCnt = _cpuCnt + (long)(_baseCnt * us);

            while (true)
            {
                QueryPerformanceCounter(ref _cpuCnt);
                if (_cpuCnt > _dlyCnt)
                    break;
            }
        }

        public static void DelayMs(int ms)
        {
            DelayUs(ms * 1000);
        }

        private static int GetTickCount()
        {
            return Environment.TickCount & Int32.MaxValue;
        }

        public static void ExDelayMs(int ms)
        {
            int endCnt = GetTickCount() + ms;
            while (endCnt > GetTickCount())
            {
                System.Windows.Forms.Application.DoEvents();
            }

        }

    }
}
