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

namespace sp {

GameTime::GameTime(unsigned long updates_per_sec)
{
	setTimeStep(updates_per_sec);
}

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

void GameTime::setTimeStep(unsigned long updates_per_sec)
{
	m_slice = Time::seconds(1.0f / ((double) updates_per_sec));
	m_max_acc = Time::seconds(1.0f / m_slice.seconds());

	reset();
}

Time GameTime::getElapsed() const
{
	return m_watch.elapsed();
}

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

	// Signal if we should tick
	return shouldTick();
}

bool GameTime::shouldTick() const
{
	// if acc is larger than one slice, we have atleast one tick.
	return m_acc > m_slice;
}

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

void GameTime::reset()
{
	m_watch.restart();
}

void GameTime::accumulateTime()
{
	m_acc += m_watch.restart();
	if (m_acc > m_max_acc) {
		m_acc = m_max_acc;
	}
}

} // namespace sp
