

#include ".\gamefps.h"
#include <PocketFrog/PocketFrog.h>

using namespace Frog;

// initialize pointer
GameFPS* GameFPS::instance_ptr_ = NULL;


GameFPS::~GameFPS(void) {}

void GameFPS::init(uint16_t wantedfps, Display *display)
{
#ifdef CONSOLE_DEBUG
	PFrogConsole::instance()->addfixedline(true,display->GetWidth()-40, 0,"");
#endif
	
	wantAutoCalculateFPS=false;

	setfps(wantedfps);
	// Default draw on top
	drawAtBottom = false;
	// init onscreen FPS counter (if requested)
	m_FPSCounter = 0;
	G_fps=0;
}


void GameFPS::setfps(uint16_t newvalue)
{
	G_min_time_per_frame = 1000/newvalue; // For wantedfps fps
    G_last_clock = PocketPC::GetTickCount();
    G_fps = newvalue; //for wantedfps fps
    G_msec = 1000/newvalue; // For wantedfps fps
}

uint16_t GameFPS::GetWantedFPS() { return G_fps; }


void GameFPS::beforescreenupdate(Display *display)
{
    while(PocketPC::GetTickCount() - G_last_clock < G_min_time_per_frame)
        Sleep(1);

    //G_msec = (uint16_t)(PocketPC::GetTickCount() - G_last_clock);	// How many ms I used to blit this time?
    //if(G_msec == 0){G_msec = 1;}									// Prevent divizion by zero
    //G_fps = 1000/G_msec;											// Updating fps
    G_last_clock = PocketPC::GetTickCount();


	// Update FPS
	if (wantAutoCalculateFPS) {
		m_FPSTicks[ m_FPSCounter & 15 ] = PocketPC::GetTickCount();
		if (m_FPSCounter > 15)
		{
			uint32_t totalTime = m_FPSTicks[ m_FPSCounter & 15 ] - m_FPSTicks[ (m_FPSCounter+1) & 15 ];
			if (totalTime == 0) totalTime = 1;
			uint16_t fps  = (uint16_t)(16000 / totalTime);
#ifdef CONSOLE_DEBUG
			PFrogConsole::instance()->setfixedline(0,"FPS: %ld", fps);
#endif
			G_fps=fps;
		}
		++m_FPSCounter;
		wantAutoCalculateFPS=false;
	}
}

uint16_t GameFPS::GetLastFPS() { 
	
	// stiamo chiedendo gli FPS quindi settiamo che vogliamo ricalcolarli
	wantAutoCalculateFPS=true;

	return G_fps; 
}
