
#include <iostream>
#include <Spectre/Game/GameTime.h>
#include <Spectre/System/System.h>

GameTime::GameTime(unsigned long updates_per_sec)
{
	m_acc = 0;
	m_current = System::getMilliseconds();
	m_lastUpdate = m_current;
	setTimeStep(updates_per_sec);
}

double GameTime::getTimeStep() const
{
	return m_slice;
}

void GameTime::setTimeStep(unsigned long updates_per_sec)
{
	m_slice = (1000.0f / ((double) updates_per_sec));

	reset();
}

unsigned long GameTime::getElapsed() const
{
	return m_current - m_lastUpdate;
}

bool GameTime::beginFrame()
{
	reset();

	accumulateTime();

	if (m_acc > m_slice) {
		m_inLoop = true;
	}
	return m_inLoop;
}

bool GameTime::tick()
{
	if (m_acc > m_slice) {
		m_acc -= m_slice;
		return true;
	}
	return false;
}

void GameTime::reset()
{
	m_lastUpdate = m_current;
	m_inLoop = false;
}

void GameTime::accumulateTime()
{
	updateTime();
	
	m_acc += (double) (m_current - m_lastUpdate);
	if (m_acc > (1000.f / m_slice)) {
		m_acc = 1000.f / m_slice;
	}
}

void GameTime::updateTime()
{
	m_current = System::getMilliseconds();

	// Just to be safe. check so we don't get a negative interval.
	if (m_current < m_lastUpdate) {
		m_lastUpdate = m_current;
	}
}