#pragma once
#include "../stdafx.h"

class glLibTimer {
	private:
		Uint32 _start_time;
		Uint32 _stop_time;
	public:
		glLibTimer() {
		}
		void mark(void) {
			_start_time = SDL_GetTicks();
		}
		double get(void) {
			_stop_time = SDL_GetTicks();
			Uint32 delta = _stop_time - _start_time;
			return delta / 1000.0;
		}
};
class glLibClock {
	private:
		glLibTimer timer;
		double* deltae;
		unsigned short _history_length;
		double _result;
		bool _must_update_result;
	public:
		glLibClock(unsigned short history_length=10) {
			_history_length = history_length;

			deltae = new double[_history_length];
			for (unsigned short i=0;i<_history_length;++i) deltae[i] = -1.0;

			_must_update_result = true;

			timer.mark();
		}
		~glLibClock() {
			delete [] deltae; deltae = NULL;
		}

		void tick(void) {
			for (unsigned short i=_history_length-1;i>0;--i) {
				deltae[i] = deltae[i-1];
			}
			deltae[0] = timer.get();
			timer.mark();

			_must_update_result = true;
		}
		void tick(double fps) {
			double time_since = timer.get();
			while (time_since+0.001<1.0/fps) {
				SDL_Delay(1);
				time_since = timer.get();
			}

			for (unsigned short i=_history_length-1;i>0;--i) {
				deltae[i] = deltae[i-1];
			}
			deltae[0] = time_since;
			timer.mark();

			_must_update_result = true;
		}
		double get_fps(void) {
			if (_must_update_result) {
				double sum = 0.0;
				unsigned short terms = 0;
				for (unsigned short i=0;i<_history_length;++i) {
					if (deltae[i]!=-1.0) {
						sum += deltae[i];
						terms++;
					}
				}
				if (terms==0) return 0.0;
				double avg = sum / terms;
				if (avg==0.0) return 0.0;
				_result = 1.0 / avg;

				_must_update_result = false;
			}
			return _result;
		}
};