/**************************************************************************
* Otter Browser: Web browser controlled by the user, not vice-versa.
* Copyright (C) 2015 Jan Bajer aka bajasoft <jbajer@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
**************************************************************************/

#include "LongTermTimer.h"

#include <QtCore/QTimerEvent>

#include <limits>

namespace Otter
{

LongTermTimer::LongTermTimer(quint64 seconds, QObject *receiver, const char *member) : QObject(receiver),
	m_secondsLeft(0),
	m_timer(0)
{
	connect(this, SIGNAL(timeout()), receiver, member);

	updateTimer(seconds);
}

void LongTermTimer::timerEvent(QTimerEvent *event)
{
	if (event->timerId() == m_timer)
	{
		killTimer(m_timer);

		m_timer = 0;

		if (m_secondsLeft == 0)
		{
			emit timeout();

			deleteLater();
		}
		else
		{
			updateTimer(m_secondsLeft, true);
		}
	}
}

void LongTermTimer::runTimer(quint64 seconds, QObject *receiver, const char *member)
{
	if (receiver && member)
	{
		new LongTermTimer(seconds, receiver, member);
	}
}

void LongTermTimer::updateTimer(const quint64 secondsLeft, const bool updateCounter)
{
	int timerValue = std::numeric_limits<int>::max();
	const quint64 milisecondsLeft = (secondsLeft * 1000);

	if (milisecondsLeft <= static_cast<quint64>(timerValue))
	{
		timerValue = milisecondsLeft;

		if (updateCounter)
		{
			m_secondsLeft = 0;
		}
	}
	else if (updateCounter)
	{
		m_secondsLeft -= (timerValue / 1000);
	}
	else
	{
		m_secondsLeft = (secondsLeft - (timerValue / 1000));
	}

	m_timer = startTimer(timerValue);
}

}
