/***************************************************************************
*   Copyright (C) 2006 by Ian Reinhart Geiser   *
*   geiseri@kde.org   *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU Library General Public License as       *
*   published by the Free Software Foundation; either version 2 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 Library 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 "server.h"
#include <QTimer>
#include <QEventLoop>

namespace KRPC
{
}

KRPC::Server::Server( QObject *parent )
: QTcpServer( parent ), m_children(0),m_maxChildren(200)
{
}


KRPC::Server::~Server()
{

}

void KRPC::Server::throttleConnections( )
{
	QEventLoop eventLoop(this);
	while( m_children > m_maxChildren )
	{
		qDebug("Waiting for %d", m_children );
		QTimer::singleShot(200, &eventLoop, SLOT(quit()));
		eventLoop.exec(QEventLoop::ExcludeSocketNotifiers);
	}
}

void KRPC::Server::incomingConnection( int socketDescriptor )
{

	throttleConnections();
	CommandThread *thread = new CommandThread(socketDescriptor, this);
	++m_children;
	connect(thread, SIGNAL(finished()), this, SLOT(finishThread()));
	connect(this, SIGNAL(exitThreads()), thread, SLOT(quit()));
	thread->start();

}

void KRPC::Server::finishThread( )
{
	sender()->deleteLater();
	--m_children;
}

void KRPC::Server::start( const QHostAddress &address, uint port )
{
	listen( address, port );
}

void KRPC::Server::stop( )
{
	close();
	emit exitThreads();

	QEventLoop eventLoop(this);

	while( m_children )
	{
		qDebug("Waiting for %d children to end...", m_children );
		QTimer::singleShot(200, &eventLoop, SLOT(quit()));
		eventLoop.exec(QEventLoop::ExcludeSocketNotifiers);
	}

}

