// [License]
// The Ariba-Underlay Copyright
//
// Copyright (c) 2008-2009, Institute of Telematics, Universität Karlsruhe (TH)
//
// Institute of Telematics
// Universität Karlsruhe (TH)
// Zirkel 2, 76128 Karlsruhe
// Germany
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE INSTITUTE OF TELEMATICS ``AS IS'' AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ARIBA PROJECT OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation
// are those of the authors and should not be interpreted as representing
// official policies, either expressed or implied, of the Institute of
// Telematics.
// [License]

#ifndef BASECOMMUNICATION_H_
#define BASECOMMUNICATION_H_

#include <ext/hash_map>
#include <ext/hash_set>
#include <map>
#include <set>
#include <vector>
#include <iostream>
#include <algorithm>
#include <boost/foreach.hpp>

#include "ariba/utility/types.h"
#include "ariba/utility/messages.h"
#include "ariba/utility/logging/Logging.h"
#include "ariba/utility/misc/Demultiplexer.hpp"

#include "ariba/communication/CommunicationEvents.h"
#include "ariba/communication/EndpointDescriptor.h"
#include "ariba/communication/networkinfo/NetworkChangeInterface.h"
#include "ariba/communication/networkinfo/NetworkChangeDetection.h"
#include "ariba/communication/networkinfo/NetworkInformation.h"
#include "ariba/communication/networkinfo/AddressInformation.h"
#include "ariba/communication/messages/AribaBaseMsg.h"
#include "ariba/communication/modules/transport/TransportProtocol.h"
#include "ariba/communication/modules/network/NetworkProtocol.h"
#include "ariba/communication/modules/network/NetworkLocator.h"

#ifndef UNDERLAY_OMNET
  #include "ariba/communication/modules/transport/tcp/TCPTransport.h"
  #include "ariba/communication/modules/network/ip/IPv4NetworkProtocol.h"
#endif

using __gnu_cxx::hash_set;
using __gnu_cxx::hash_map;

using std::cout;
using std::set;
using std::map;
using std::vector;
using std::pair;
using std::make_pair;
using std::find;

using ariba::communication::NetworkChangeDetection;
using ariba::communication::NetworkChangeInterface;
using ariba::communication::NetworkInterfaceList;
using ariba::communication::NetworkInformation;
using ariba::communication::AddressInformation;
using ariba::communication::AddressList;
using ariba::communication::AribaBaseMsg;
using ariba::communication::CommunicationEvents;

using ariba::utility::Demultiplexer;
using ariba::utility::QoSParameterSet;
using ariba::utility::SecurityParameterSet;
using ariba::utility::Address;
using ariba::utility::LinkID;
using ariba::utility::LinkIDs;
using ariba::utility::Message;
using ariba::utility::MessageReceiver;
using ariba::utility::seqnum_t;

using ariba::communication::TransportProtocol;
using ariba::communication::NetworkProtocol;
using ariba::communication::NetworkLocator;
#ifndef UNDERLAY_OMNET
  using ariba::communication::IPv4NetworkProtocol;
  using ariba::communication::TCPTransport;
#endif

namespace ariba {
namespace communication {

/**
 * This class implements the Ariba Base Communication<br />
 *
 * Its primary task is to provide an abstraction to existing
 * protocols and addressing schemes.
 *
 * @author Sebastian Mies, Christoph Mayer
 */
class BaseCommunication : public MessageReceiver, NetworkChangeInterface {
	use_logging_h(BaseCommunication);
public:

	/**
	 * Default ctor that just creates an empty
	 * non functional base communication
	 */
	BaseCommunication();

	/**
	 * Default dtor that does nothing
	 */
	virtual ~BaseCommunication();

	/**
	 * Startup the base communication, start modules etc.
	 */
	void start(const NetworkLocator* _locallocator, const uint16_t _listenport);

	/**
	 * stop the base communication, stop modules etc.
	 */
	void stop();

	/**
	 * Establishes a link to another end-point.
	 */
	const LinkID establishLink(
		const EndpointDescriptor& descriptor,
		const LinkID& linkid = LinkID::UNSPECIFIED,
		const QoSParameterSet& qos = QoSParameterSet::DEFAULT,
		const SecurityParameterSet& sec = SecurityParameterSet::DEFAULT
	);

	/**
	 * Drops a link.
	 *
	 * @param The link id of the link that should be dropped
	 */
	void dropLink(const LinkID link);

	/**
	 * Sends a message though an existing link to an end-point.
	 *
	 * @param lid The link identifier
	 * @param message The message to be sent
	 * @return A sequence number for this message
	 */
	seqnum_t sendMessage(const LinkID lid, const Message* message);

	/**
	 * Returns the end-point descriptor
	 *
	 * @param link the link id of the requested end-point
	 * @return The end-point descriptor of the link's end-point
	 */
	const EndpointDescriptor& getEndpointDescriptor( const LinkID link = LinkID::UNSPECIFIED ) const;

	/**
	 * Get local links to the given endpoint of all local link
	 * using the default parameter EndpointDescriptor::UNSPECIFIED
	 * @param ep The remote endpoint to get all links to.
	 * @return List of LinkID
	 */
	LinkIDs getLocalLinks( const EndpointDescriptor& ep = EndpointDescriptor::UNSPECIFIED ) const;

	/**
	 * Registers a receiver.
	 *
	 * @param _receiver The receiving side
	 */
	void registerMessageReceiver( MessageReceiver* _receiver );

	/**
	 * Unregister a receiver.
	 *
	 * @param _receiver The receiving side
	 */
	void unregisterMessageReceiver( MessageReceiver* _receiver );

	void registerEventListener( CommunicationEvents* _events );
	void unregisterEventListener( CommunicationEvents* _events );

protected:

	/**
	 * Called from the Transport when async items
	 * from the SystemQueue are delivered
	 */
	virtual bool receiveMessage( const Message* message, const LinkID& link, const NodeID& node );

	/**
	 * Called when a network interface change happens
	 */
	virtual void onNetworkChange( const NetworkChangeInterface::NetworkChangeInfo& info );

private:

	/**
	 * A link descriptor consisting of the
	 * end-point descriptor and currently used locator and
	 * message receiver
	 */
	class LinkDescriptor {
	public:
		static const LinkDescriptor UNSPECIFIED;

		LinkDescriptor() :
			localLink(LinkID::UNSPECIFIED),
			localLocator(NULL),
			remoteLink(LinkID::UNSPECIFIED),
			remoteLocator(NULL),
			remoteEndpoint(EndpointDescriptor::UNSPECIFIED),
			linkup(false) {
		}

		LinkDescriptor(const LinkID& _localLink, const NetworkLocator*& _localLocator,
				const LinkID& _remoteLink, const NetworkLocator*& _remoteLocator,
				const EndpointDescriptor& _remoteEndpoint, bool _linkup ) :
			localLink(_localLink),
			localLocator(_localLocator),
			remoteLink(_remoteLink),
			remoteLocator(_remoteLocator),
			remoteEndpoint(_remoteEndpoint),
			linkup(_linkup) {
		}

		LinkDescriptor( const LinkDescriptor& desc ) :
			localLink(desc.localLink),
			localLocator(desc.localLocator),
			remoteLink(desc.remoteLink),
			remoteLocator(desc.remoteLocator),
			remoteEndpoint(desc.remoteEndpoint),
			linkup(desc.linkup) {
		}

		bool isUnspecified() const {
			return (this == &UNSPECIFIED);
		}

		LinkID 					localLink;
		const NetworkLocator* 	localLocator;
		LinkID 					remoteLink;
		const NetworkLocator* 	remoteLocator;
		EndpointDescriptor 		remoteEndpoint;

		bool 					linkup;
	};

	/**
	 * Link management: add a link
	 */
	void addLink( const LinkDescriptor& link );

	/**
	 * Link management: remove alink
	 */
	void removeLink( const LinkID& localLink );

	/**
	 * Link management: get link information using the local link
	 */
	LinkDescriptor& queryLocalLink( const LinkID& localLink ) const;

	/**
	 * Link management: get link information using the remote link
	 */
	LinkDescriptor& queryRemoteLink( const LinkID& remoteLink ) const;

	/**
	 * Link management: list of links
	 */
	typedef vector<LinkDescriptor> LinkSet;

	/**
	 * Link management: the set of currently managed links
	 */
	LinkSet linkSet;

	/**
	 * The message receiver
	 */
	MessageReceiver* messageReceiver;

	/**
	 * The local end-point descriptor
	 */
	EndpointDescriptor localDescriptor;

	/**
	 * Network information and protocol
	 */
	NetworkProtocol* network;

	/**
	 * Transport information and protocol
	 */
	TransportProtocol* transport;

#ifndef UNDERLAY_OMNET
	/**
	 * Detect changes in the routing/interface, etc.
	 * stuff needed for mobility detection
	 */
	NetworkChangeDetection networkMonitor;
#endif

	/**
	 * The local listen port
	 */
	uint16_t listenport;

	typedef set<CommunicationEvents*> EventListenerSet;
	EventListenerSet eventListener;

	seqnum_t currentSeqnum;
};

}} // namespace ariba, communication

#endif /*BASECOMMUNICATION_H_*/
