/***************************************************************************
                          clisten.cpp  -  description
                             -------------------
    begin                : Fri Mar 22 2002
    copyright            : (C) 2002-2003 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 "clisten.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifndef WIN32
#include <unistd.h>
#endif

#include "cmanager.h"

/** */
CListen::CListen()
{
	m_pListenCallback = 0;
	m_pCallback = 0;
}

/** */
CListen::~CListen()
{
	SetCallBackFunction(0);
	
	StopListen();
}

/** */
int CListen::StartListen( int port, CString ip, bool manager )
{
	int err;

	m_Mutex.Lock();

	err = 0;

	if ( (CManager::Instance() == 0) && (manager) )
	{
		err = -1;
	}
	else if ( Listen( port, ip ) != 0 )
	{
		err = -1;
	}
	else if ( manager )
	{
		m_pCallback = new CCallback0<CListen>( this, &CListen::Callback );
		CManager::Instance()->Add( m_pCallback );
	}

	m_Mutex.UnLock();
	
	return err;
}

/** */
void CListen::StopListen()
{
	m_Mutex.Lock();
	
	if ( m_pCallback )
	{
		if ( CManager::Instance() )
			CManager::Instance()->Remove( m_pCallback );
		delete m_pCallback;
		m_pCallback = 0;
	}

	m_Mutex.UnLock();
	
	Disconnect();
}

/** */
int CListen::Callback()
{
	int fd;

	m_Mutex.Lock();
	
	fd = Accept();
    
	if ( fd != -1 )
	{
		if ( m_pListenCallback != 0 )
		{
			m_pListenCallback->notify(fd);
		}
		else
		{
			DC_ListenCallBack(fd);
		}
	}

	m_Mutex.UnLock();

	return 0;
}
