
/*
* timers-c.cc     : Timer Management C-language API
* authors         : John Heidemann
*
* Copyright (C) 2000-2001 by the Unversity of Southern California
* $Id: timers-c.cc,v 1.1 2002/04/30 17:44:37 johnh Exp $
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* 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, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*
*/

#include <assert.h>
#include <map>

#include "timers.hh"
#include "timers-c.h"



class TimersCCallback : public TimerCallbacks {
protected:
	TimerCallback_t cb_;
	void *p_;
public:
	TimersCCallback(TimerCallback_t cb, void *p) : cb_(cb), p_(p) {};
	int expire(handle hdl);
};

static Timers timers;
map<int,TimersCCallback*> handles_to_callbacks;



int
TimersCCallback::expire(hdl)
{
	int res = (*cb_)(hdl, p_);
	assert(handles_to_callbacks.find(hdl) != handles_to_callbacks.end());
	handles_to_callbacks.erase(hdl);
	if (res < 0)
		delete this;
}

int
Timers_AddTimer(int timeout, TimerCallback_t cb, void *p)
{
	TimersCCallback *cb = new TimersCCallback(cb, p);
	int hdl = timers.AddTimer(timeout, p);
	handles_to_callbacks[hdl] = cb;
	return hdl;
}

int
Timers_RemoveTimer(int handle)
{
	if (handles_to_callbacks.find(hdl) != handles_to_callbacks.end())
		erase.handles_to_callbacks(hdl);
	return (int) timers.RemoveTimer(handle);
}

void
Timers_NextTimerTime(struct timeval *tv)
{
	timers.NextTimerTime(tv);
}

void
Timers_ExecuteNextTimer()
{
	timers.ExecuteNextTimer();
}

