//Copyright (C) 2007 SiegeLord
//See ReadMe.txt and License.txt for copying information

#include "../include/engine/timer.h"

#ifndef ALLEGRO_WINDOWS

#include <sys/time.h>

#else

#include <winalleg.h>
#include <mmsystem.h>
#pragma comment(lib, "Winmm.lib")

#endif

float g_fDelta;
float g_fRawDelta;//unaffected by speed, could be used for gui etc
float g_fCurTime;//this now represents the ammout of time the program was running
float g_fSpeed;

int g_nInitTime;//we subtract this from the time returned by the timer thingamagings... to improve accuracy of the float used
				//it just so happened that under linux the number of seconds is very big, hogging all of the digits needed
				//I just think it is a good idea

void InitTimer()
{
	install_timer();
	g_fDelta = 1.0f;
	g_fCurTime = 0.0f;
	g_fSpeed = 1.0f;
	g_fRawDelta = 1.0f;
	#ifndef ALLEGRO_WINDOWS

		struct timeval time;
		gettimeofday(&time, NULL);
		g_nInitTime = time.tv_sec;

	#else

		int n = timeGetTime();
		g_nInitTime = n;

	#endif

	Tick();
	Tick(); //init delta etc etc
}

float GetTime()
{

#ifndef ALLEGRO_WINDOWS

	struct timeval time;

	gettimeofday(&time, NULL);

	return float(time.tv_sec - g_nInitTime) + float(time.tv_usec) / 1000000.0f;

#else

	int n = timeGetTime();

	return float(n - g_nInitTime) / 1000.0f;

#endif

}

void Tick()
{
	float new_time = GetTime();

	g_fRawDelta = new_time - g_fCurTime;
	g_fDelta = g_fSpeed * g_fRawDelta;
	g_fCurTime = new_time;


}

//wait until is like Tick, but it can cap the framerate by calling the supplied callback function
//it could be logic or otherwise
void WaitUntil(float delta_target, void (*proc)(void* param), void* param, bool execute_at_least_once)
{
	float new_time = GetTime();
	float delta = new_time - g_fCurTime;

	if(delta > delta_target)
	{
		if(execute_at_least_once)
			proc(param);
		else
		{
			g_fRawDelta = delta;
			g_fDelta = g_fSpeed * g_fRawDelta;
			g_fCurTime = new_time;

			return;
		}
	}

	float old_time = g_fCurTime;
	while(delta < delta_target)
	{
		new_time = GetTime();
		delta = new_time - old_time;

		g_fRawDelta = delta;
		g_fDelta = g_fSpeed * g_fRawDelta;
		g_fCurTime = new_time;

		proc(param);
	}
}
