/*  $Id: timer_generic.cpp,v 1.11 2003/07/20 22:30:53 grumbel Exp $
**
**  ClanLib Game SDK
**  Copyright (C) 2003  The ClanLib Team
**  For a total list of contributers see the file CREDITS.
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  This library 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
**  Lesser General Public License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
**
*/

#include "Core/precomp.h"
#include "API/Core/System/timer.h"
#include "API/Core/System/system.h"

CL_Timer::CL_Timer(unsigned long _interval)
: interval(_interval), last_time(0), enabled(false)
{
}

void CL_Timer::keep_alive()
{
	if (!enabled)
		return;

	unsigned long cur = CL_System::get_time();
	if (last_time > cur)
		last_time = cur; // The counter has overflowed the variable - reset it
		
	while (cur >= last_time + interval)
	{
		sig_timer()();
		last_time += interval;
	}
}

void CL_Timer::enable()
{
	enabled = true;
	last_time = CL_System::get_time();
}

void CL_Timer::disable()
{
	enabled = false;
}

bool CL_Timer::is_enabled()
{
	return enabled;
}

void CL_Timer::set_interval(unsigned long interval)
{
	this->interval = interval;
	last_time = CL_System::get_time();
}

unsigned long CL_Timer::get_interval()
{
	return interval;
}

CL_Signal_v0 &CL_Timer::sig_timer()
{
	return signal_timer;
}
