
/* --------------------------------------------------------------------------------
 #
 #	TTcp.h
 #	project : MA_Plugin2
 #	author  : Pasi Mankinen
 #	date		: 2008-02-13
 #
 # --------------------------------------------------------------------------------*/


#ifndef TcpHPP
#define TcpHPP

#include "Includes.h"

class TTcp {
private:
	TPointerArray<TServer> 	*tcpServers;		// list of listen sockets
	TPointerArray<TSocket> 	*tcpSockets;		// list of outgoing sockets
  
	TServer   *currentServer;				// last selected server
  
	// socket_type_t						currentSocketType;
	long		nextInConnectionId;
	long		lastInConnectionId;
	long		nextServerConnectionId;
	long		lastServerConnectionId;
	long		nextOutConnectionId;
	long		lastOutConnectionId;
  
  // pollset
  long                pollsetIdNext;     
  long                pollsetMaxSize;
  long                pollsetOption;
  apr_pool_t         *pollsetAprMemoryPool;
  apr_pollset_t      *pollsetAprId;
  
  
protected:
  
public:
	
	TSocket   *currentSocket;				// last selected socket
  long      currentSocketNum;
    
  long                pollsetId;         // unique running id
  long                pollCount;         // how many times has been polled
  long                pollReceiveCount;  // how many times has been been received events  
  const apr_pollfd_t* pollsetReturn_pfd; // must NEVER set this
	std::vector<apr_socket_t*>   pollSocketApr;    // apr poll sockets  
	std::vector<apr_int16_t>     pollSocketOption; // apr poll sockets
	//std::vector<long>   pollSocketId;     // not in use currently
  
  long AddSocketsToPollset( void );
  void ClearPollset( void );
  long CreatePollset( long pollsetMaxSizeIn, long optionIn );
  void DestroyPollset( void );
  // long RemoveFromPollset( apr_socket_t *socket );
  long Poll();
  inline long GetPollCount() { return pollCount; }
  inline long GetReceiveCount() { return pollReceiveCount; }
  
  
  // socket
  
	TTcp();
	virtual ~TTcp();
  
	TSocket*	GetSocketByRef( long socketNum, wstring callingMethod );
	TServer*	GetServerByRef( long serverNum, wstring callingMethod );
	
	long			GetOSSocket( long socketNum );
	long			GetStatus( long socketNum );
	long			NewOutgoingConnectionOpen( wstring address, long port, wstring options );							 // called from MA_TCP_Connect
	long			NewIncomingConnection( TServer *server, wstring options ); // called from MA_TCP_Accept
	
	// socket_type_t CurrentSocketType();		// called from MA_TCP_Close
	long					SocketAdd( TSocket *socket, socket_type_t type );		// called from MA_TCP_Accept, MA_TCP_Connect
	long					SocketClose( TSocket *socket );	// called from MA_TCP_Close
	TServer*			ServerAdd( wstring address, long portNum, wstring options ); // called from MA_TCP_Listen
	long					ServerDelete( TServer *server );	// called from MA_TCP_Close
  
};

#endif