#include "stopwatch.h"
#include "util.h"

#include <QLabel>

StopWatch::StopWatch()
{}

void StopWatch::start()
{
	m_elapsed.start();
	connect(&m_timer, SIGNAL(timeout()), this, SLOT(updateTimer()));
	m_timer.start(18);
}

void StopWatch::stop()
{
	m_timeTaken = m_elapsed.elapsed();
	m_timer.stop();
	updateTimer();
	m_elapsed.invalidate();
}

void StopWatch::updateTimer()
{
	if (m_elapsed.isValid()) {
		qint64 ms = m_elapsed.elapsed();
		if (m_output) {
			m_output->setText(msfloatToHumanReadableString(ms));
		}


		if (m_timer.isActive()) {
			int interval;
			if (ms >= 10000) {
				int rem = ms % 1000;
				interval = 1000 - rem;
			}
			else if (ms >= 1000)
				interval = 100;
			else
				interval = 18;

			if (interval != m_timer.interval())
				m_timer.setInterval(interval);
		}
	}
}

void StopWatch::setOutputLabel(QLabel *label)
{
	m_output = label;
}

qint64 StopWatch::elapsed()
{
	qint64 result;
	if (m_elapsed.isValid())
		result = m_elapsed.elapsed();
	else
		result = m_timeTaken;

	return result;
}
