/* Copyright (C) 2007  Mikko Sysikaski <mikko.sysikaski@gmail.com>
 * This program is free software distributed under GNU General Public License
 * version 3 or (at your option) any later version.
 * No warranty of any kind is provided. See the accompanying file COPYING for details.
 */

#include "lcdcounter.h"
#include "lcd.h"
#include "glscreen.h"
#include "SDL.h"
#include <GL/gl.h>

static const int FPS_INTERVAL=500;

LCDCounter::LCDCounter()
{
	reset(-1);
}

void LCDCounter::start()
{
	if (m_startTime == -1)
		m_startTime = SDL_GetTicks();
/*	else {
		m_startTime += SDL_GetTicks()-m_stopTime;
	}*/
	m_stopTime = -1;
}
void LCDCounter::reset(int maxTime)
{
	m_startTime = m_stopTime = -1;
	m_maxTime = maxTime;
	m_lastSec = SDL_GetTicks()/1000;
}
void LCDCounter::update()
{
	glDisable(GL_DEPTH_TEST);
	glDepthMask(0);
	glDisable(GL_TEXTURE_2D);
	glDisable(GL_LIGHTING);
	Mutex2D mutex;
	glLoadIdentity();

	int now;
	if (m_stopTime == -1) {
		int time = SDL_GetTicks();
		now = time-m_startTime;

		if (time > (m_lastSec+1)*FPS_INTERVAL) {
		//	printf("updating\n");
			m_fps = m_frames * 1000 / FPS_INTERVAL;
			m_frames = 0;
			m_lastSec = time/FPS_INTERVAL;
		}
		++m_frames;
	}
	else
		now = m_stopTime-m_startTime;

	if (m_maxTime >= 0 && now > m_maxTime)
		glColor3f(1, 0, 0);
	else
		glColor3f(0, 1, 0);
	glTranslatef(-0.9, 0.8, 0);
	glScalef(0.1, 0.1, 1);
	char buf[64];
	snprintf(buf, sizeof(buf), "%.02f", 0.001f*now);
	LCD::print(buf, LCD::LEFT);
	if (m_maxTime >= 0) {
		glColor3f(0.9, 0, 0.6);
		glTranslatef(0, -1.2, 0);
		snprintf(buf, sizeof(buf), "%.02f", 0.001f*m_maxTime);
		LCD::print(buf, LCD::LEFT);
	}

	if (m_stopTime == -1) {
		glLoadIdentity();
		glTranslatef(0.95, 0.8, 0);
		glScalef(0.1, 0.1, 1);
		glColor3f(1, 0, 1);

		snprintf(buf, sizeof(buf), "%i", m_fps);
		LCD::print(buf, LCD::RIGHT);
	}
	
	glEnable(GL_DEPTH_TEST);
	glDepthMask(1);
}
void LCDCounter::stop()
{
	if (m_stopTime < 0)
		m_stopTime = SDL_GetTicks();
}
int LCDCounter::getTime() const
{
	if (m_stopTime == -1)
		return SDL_GetTicks()-m_startTime;
	return m_stopTime-m_startTime;
}
