#pragma once

using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Diagnostics;


namespace SampleCallback {
	public ref class CFPS
	{
	public:
		CFPS(int nSampleCount) : m_nCurPos(0), m_nSampleCount(0), m_nFrequency(0), m_bEnoughDataExist(false)
		{
            m_nSampleCount = nSampleCount;
            m_pnCounterLog = new long long[m_nSampleCount];
            QueryPerformanceFrequency(m_nFrequency);
		}
		~CFPS()
		{
			if (m_pnCounterLog)
			{
				delete[] m_pnCounterLog;
			}
		}
		void Check()
        {
            QueryPerformanceCounter(m_pnCounterLog[m_nCurPos]);
            m_nCurPos = m_nCurPos + 1;
            if (m_nSampleCount <= m_nCurPos)
            {
                m_bEnoughDataExist = true;
                m_nCurPos = 0;
            }
        }
        double GetFPS()
        {
            int nStartPos = m_nCurPos;
            int nEndPos = m_nCurPos - 1;
            if (nEndPos < 0)
            {
                nEndPos = m_nSampleCount - 1;
            }

            int nCurSampleCount = m_nSampleCount - 1;

            if (!m_bEnoughDataExist)
            {
                nStartPos = 0;
                nEndPos = m_nCurPos - 1;
                nCurSampleCount = m_nCurPos - 1;
            }

            double dblReval = 0.0;

            if (1 <= nCurSampleCount)
            {
				System::Int64 nDelta = m_pnCounterLog[nEndPos] - m_pnCounterLog[nStartPos];
                dblReval = nCurSampleCount * m_nFrequency / (double)nDelta;
            }

            return (dblReval);
        }

        void Reset()
        {
            m_bEnoughDataExist = false;
            m_nCurPos = 0;
        }
	protected:

		[System::Runtime::InteropServices::DllImport("kernel32.dll")]
		static bool QueryPerformanceCounter(long long% lpPerformanceCount);

        [System::Runtime::InteropServices::DllImport("kernel32.dll")]
        static bool QueryPerformanceFrequency(long long% lpFrequency);

        bool m_bEnoughDataExist;
        int m_nCurPos;
        int m_nSampleCount;
        long long m_nFrequency;
        long long *m_pnCounterLog;
	};
}
