/**
 * @file TcpipServer.h
 * This header file defines the TcpipServer class.
 * @author Tomas Urban
 * @version 0.3
 * @date 23/07/2009
 */
#ifndef TCPIP_SERVER_H
#define TCPIP_SERVER_H

#include "TcpipDefs.h"
#include "Helper/Singleton.h"
#include "ConnectionController.h"
#include <list>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>

/**
 * Simple class for creating a listening socket on a certain port and handling incoming connection requests
 * from clients.
 */
class TcpipServer : public Singleton<TcpipServer>
{
private:
	SOCKET_TYPE m_hListeningSocket;
	boost::mutex m_mutex;
	boost::condition m_operationEnded;
	std::list<ConnectionController *> m_lActiveControllers;

	class ConnectionHandler
	{ 
	private:
		SOCKET_TYPE m_hSocket;
	public:
		ConnectionHandler(SOCKET_TYPE hSocket);
		void operator()();
	}; 

	friend class Singleton<TcpipServer>;
	TcpipServer(void);
	void OnExit();
	static void OnExit(int nSig);
public:
	/**
	 * Default port number
	 */
	static int const DEFAULT_PORT = 5501;
	~TcpipServer(void);
	/**
	 * The method opens a TCP/IP socket on a specified port and start listening on it. When a connection
	 * request is accepted, a new thread is created for handling the communication with the client.
	 * The method is designed as blocking and it returns only if an error occurs or on a client 
	 * (i.e. lower tester) request.
	 * @param nPort Port on which the instance should listen
	 */
	void Run(int nPort);
};

#endif
