// DWBS ------------------------------------------------------------------ DWBS
//
// PLATFORM		: ALL
// PRODUCT		: BIT_DEMON
// VISIBILITY	: PUBLIC
//
// DWBS ------------------------------------------------------------------ DWBS

#ifndef BD_CONNECTION_STORE_H
#define BD_CONNECTION_STORE_H

#include <bdCore/bdCore.h>
#include <bdSocket/bdSocketConfig.h>

// NOTE: Errors pointing to this line probably indicate that you need: 
//       #include <bdConnection/bdConnection.h>
//       in your *.cpp file
BD_REFERENCE(bdConnection);
BD_REFERENCE(bdInitChunk);

class bdSecurityKeyMap;
class bdConnectionListener;
class bdSocketRouter;

class bdConnectionStore
{
	public:

		BD_DECLARE_NEW_AND_DELETE_OPERATORS

		/// Constructor
		bdConnectionStore(bdSocketRouter *socket,
						  bdCommonAddrRef me,
						  bdSecurityKeyMap * keyMap,
						  bdECCKey *const key = BD_NULL);

		/// Destructor
		~bdConnectionStore();

		/// Register a connection listener with the connection store.
		/// The connection listener will automatically be registered
		/// with all *new* connections.
		/// \param listener[in] The listener to be registered
		void registerListener(bdConnectionListener *listener);

		/// Removes a connection listener from the connection store.
		/// This does not remove them from individual connections.
		/// \param listener[in] The listener to be unregistered
		void unregisterListener(bdConnectionListener *listener);

		///////////////////////////////////////////////////////////////////////
		//
		// Methods for creating and destroying connections.
		//

		bdConnectionRef create(bdCommonAddrRef addr, const bdSecurityID &secID);

		void remove(bdConnectionRef connection);

		void closeAll();

		void disconnectAll();

		///////////////////////////////////////////////////////////////////////
		//
		// Methods for flushing and filling connections.
		//

		/// Call to flush all available messages to the network.
		/// This loops through all bdConnections and calls flush on each of
		/// them.
		bdBool flushAll();

		/// Flushes all data available on connection.
		bdUInt flush(bdConnection& connection);

		/// Receive data from the network and find the matching connection.
		/// Set conn to the matching connection.
		bdBool receiveFrom(bdConnectionRef &conn);

	protected:

		bdSocketRouter *m_socket;

		bdSecurityKeyMap *m_keyMap;

		bdECCKey* m_ECCKey;

		bdCommonAddrRef m_me;

		bdHashMap<bdAddrHandleHashmapWrapper, bdConnectionRef, bdAddrHandleHashmapWrapper> m_connectionMap;

		/// A container of all the registered connection listeners.
		bdFastArray<bdConnectionListener*> m_listeners;
};


#endif // BD_CONNECTION_STORE_H
