/***************************************************************************
                           cmanager.cpp  -  description
                             -------------------
    begin                : Thu Jan 23 2003
    copyright            : (C) 2003-2005 by Mathias Küster
    email                : mathen@users.berlios.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include "cmanager.h"

#ifndef WIN32
#include <sys/time.h>
#endif
#include "platform.h"

#include "ccallback.h"

/** */
CManager::CManager()
{
	Start();
}

/** */
CManager::~CManager()
{
	SetInstance(0);
	Stop();
}

/** */
void CManager::Add( _CCallback0 * callback )
{
	if ( callback )
	{
		m_CallbacksMutex.Lock();
		m_Callbacks.Add(callback);
		m_CallbacksMutex.UnLock();
	}
}

/** */
void CManager::Remove( _CCallback0 * callback )
{
	if ( callback )
	{
		m_CallbacksMutex.Lock();
		m_Callbacks.Remove(callback);
		m_CallbacksMutex.UnLock();
	}
}

/** */
void CManager::Thread()
{
	struct timeval tv_old, tv_new;
	_CCallback0 * callback = 0;
	unsigned int i;

	gettimeofday(&tv_old, NULL);

	while( true )
	{
		m_CallbacksMutex.Lock();

		callback = m_Callbacks.Next(callback);

		m_CallbacksMutex.UnLock();

		if ( !callback )
		{
			break;
		}

		callback->notify();
	}

	gettimeofday(&tv_new, NULL);

	i = 0;

	if ( (tv_new.tv_sec - tv_old.tv_sec) == 0 )
	{
		i = (tv_new.tv_usec - tv_old.tv_usec);

		if ( i < 5000 )
		{
			i = 10 - (i/1000);
		}
		else
		{
			i = 0;
		}
	}

	//malloc_stats();

	//printf("%d %d %d\n",i,tv_new.tv_sec - tv_old.tv_sec,(tv_new.tv_usec - tv_old.tv_usec)/1000);

	NanoSleep(i);
}
