/* Network-Integrated Multimedia Middleware (NMM)
 * http://www.motama.com/nmm.html
 *  
 * Copyright (C) 2006-2007
 * Motama GmbH, Saarbruecken, Germany
 * http://www.motama.com
 *  
 * This file is part of NMM. 
 * 
 * NMM is free software; you can redistribute it and/or modify it    
 * under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; only version 2 of the License.      
 * 
 * NMM 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 General Public License 
 * along with NMM; if not, write to the Free Software Foundation,    
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */

#ifndef NMM_PACKET_I_NET_STREAM_HPP
#define NMM_PACKET_I_NET_STREAM_HPP NMM_PACKET_I_NET_STREAM_HPP

#include "nmm/nmm_prefix.hpp"

#include "INetStream.hpp"

#include "nmm/comm/serialize/TValue.hpp"

#include "nmm/utils/thread/ThreadMutex.hpp"

#include "visibility.hpp"

namespace NMM {

  class DLLEXPORT PacketHeader;

  /** Packetized network input stream.
   * This class implements a network input stream which splits data into packets
   * for consistent, ordered all-or-nothing transmission on unreliable channels.
   *
   * This is the network receiver part of the packetized network stream.
   * It reads complete packets from the network, checks if they are consistent
   * and reconstructs messages using queued packets.
   * Packets belonging to messages which can no longer be delivered in-order
   * are discarded.
   *
   * This stream also gathers statistics of the packetized transmission.
   *
   * @see PacketHeader, PacketONetStream, UDPStrategy, UDPBroadcaster
   */
  class DLLEXPORT PacketINetStream
    : public INetStream
  {
  public:
    /** @name Constructor & Destructor
     */
    //@{
    /** Constructor.
     */
    PacketINetStream();

    /** Copy Constructor.
     *
     * @param other Object to copy from
     */
    PacketINetStream(const PacketINetStream& other);

    /** Virtual destructor.
     */
    virtual ~PacketINetStream();

    /** virtual copy constructor.
     *
     * @return A copy of this object which has the same type
     */
    virtual PacketINetStream* copy() const;
    //@}
    
    /** @name IStream methods
     */
    //@{
    /** Check if this stream is empty.
     * This method checks if this stream contains no data to read.
     * If this method returns @c true, serialization operations will fail.
     *
     * This implementation always returns @c true.
     *
     * @return @c true if this stream is empty, @c false otherwise
     */
    virtual bool isEmpty() const { return true; }

    /** Read data for serialization.
     * This method must be called before using the serialization operators.
     * It fetches data internally.
     *
     * This implementation reconstructs a new message from a set of queued packets that
     * make up a complete message.
     *
     * This method may only be called after receivePacket has returned true.
     */
    virtual void readData();
    //@}
    
    /** @name INetStream methods
     */
    //@{
    /** Handle incoming data.
     * This method is notifies the stream that data can be read from the socket.
     * The stream internally analyzes the data and checks if there is any actual data that can be read.
     *
     * This implementation reads a new packet from the socket.
     * It returns @c true if and only if a new message can be reconstructed.
     *
     * @return @c true if there is data to read, @c false otherwise
     */
    virtual bool receivePacket();
    //@}
    
    /** @name Protocol Options
     */
    //@{
    /** Set the maximum size of a packet.
     * This method sets the maximum size of the data in a packet.
     * This value, together with the size of the packet header, may not exceed the maximum transmission unit (MTU)
     * of the underlying channel.
     *
     * @param size Maximum packet size in bytes
     */
    virtual void setPacketSize(const unsigned int& size);
    
    /** Get the maximum size of a packet.
     * This method gets the maximum size of the data in a packet.
     *
     * @return Maximum packet size in bytes
     */
    virtual unsigned int getPacketSize() const;

    /** Set maximum number of partial messages.
     * This method sets the maximum number of different messages of which packets
     * may be queued at the receiver side. If packets belonging to more partial messages
     * are queued, all packets belonging the the oldest message are discarded.
     * This behaviour can be disabled by calling setDiscardOldPackets().
     *
     * @param max_partial Maximum number of partial messages
     */
    virtual void setMaxPartialMessages(const unsigned int& max_partial);

    /** Get maximum number of partial messages.
     * This method gets the maximum number of different messages of which packets
     * may be queued at the receiver side. If packets belonging to more partial messages
     * are queued, all packets belonging the the oldest message are discarded.
     * This behaviour can be disabled by calling setDiscardOldPackets().
     *
     * @return Maximum number of partial messages
     */
    virtual unsigned int getMaxPartialMessages() const;

    /** Enable or disable discarding of old packets.
     * This method enables or disables discarding of old packets if packets of too many
     * partial messages are queued.
     * By default, discarding of old packets is enabled.
     *
     * @param discard @c true to enable, @c false to disable discarding of old packets
     */
    virtual void setDiscardOldPackets(const bool& discard) { __discard_old_packets.setValue(discard); }

    /** Check if discarding of old packets is enabled or disabled.
     * This method returns a flag which indicates if discarding of old packets if packets of too many
     * partial messages are queued is enabled or disabled.
     * By default, discarding of old packets is enabled.
     *
     * @return @c true if discarding of old packets is enabled, @c false otherwise
     */
    virtual bool getDiscardOldPackets( ) const { return __discard_old_packets.getRValue(); }

    //@}
    
    /** @name Protocol Statistics
     */
    //@{
    /** Reset all statistics.
     * This method resets all statistics that can be queried by the other methods
     * to their initial values.
     */
    virtual void resetStatistics();

    /** Get total number of received bytes.
     * This method returns the total number of bytes received over the network.
     *
     * @return Total number of received bytes
     */
    virtual unsigned int getTotalReceivedBytes() const;

    /** Get total number of received packets.
     * This method returns the total number of packets which have been received from the network.
     *
     * @return Total number of received packets
     */
    virtual unsigned int getTotalReceivedPackets() const;

    /** Get total number of discarded packets.
     * This method returns the total number of packets which have been discarded because they arrived
     * out of order.
     *
     * @return Total number of discarded packets
     */
    virtual unsigned int getTotalDiscardedPackets() const;

    /** Get total number of lost packets.
     * This method returns the total number of packets which are considered lost because they
     * were expected but did not arrive.
     *
     * @return Total number of lost packets
     */
    virtual unsigned int getTotalLostPackets() const;
    //@}
    
  protected:
    /** Subclass constructor.
     *
     * @param ti Type information
     */
    PacketINetStream(const TypeInfo& ti);
    
    /** Internal method to read the data.
     */
    virtual void readValue(void*, size_t);
    
    /** Update attributes after deserialization.
     */
    virtual void updateAttributes();
    
  private:
    /** A buffer to store packet data. */
    typedef vector<char> Packet;    

    /** Read a packet from the socket.
     * This method reads a packet from the socket and stores it in the given buffer.
     *
     * @param packet Returns the packet data, including header
     * @return Number of bytes received
     */
    unsigned int readPacket(void* packet);

    /** Check if a message can be reconstructed.
     * This method checks if a mesasge can be reconstructed from queued packets.
     *
     * @return @c true if a message can be reconstructed, @c false otherwise
     */
    bool checkForCompleteMessage();

    /** Discard old packets.
     * This method discards packets using the discarding algorithm of this stream
     * described in the documentation of setMaxPartialMessages().
     */
    void discardOldPackets();

    /** Register attributes for serialization.
     */
    void registerAttributes();
    
  private:
    /* Begin> Packet buffers */
    ThreadMutex __packet_mutex;             ///< Mutex to protect packet buffers
    TValue<nmm_uint32> __max_packet_size;          ///< Maximum packet size
    TValue<nmm_uint32> __max_partial;              ///< Maximum number of partial messages in queue
    TValue<nmm_bool> __discard_old_packets;     ///< Discarding old packages is enabled

    Packet __i_packet;                      ///< Input packet buffer
    bool __stream_socket;                   ///< Socket is a stream socket
    /* End< Packet buffers */
    
    /* Begin> Incoming packet queue */
    ThreadMutex __packet_queue_mutex;       ///< Mutex to protect packet queue
    list<Packet> __i_packets;               ///< List of queued packets
    /* End< Incoming packet queue */
    
    /* Begin> Messages */
    vector<char> __i_message;               ///< Current input message buffer
    int __i_message_pos;                    ///< Write position for input message
    int __i_message_id;                     ///< Last input message id
    /* End< */
    
    /* Begin> Statistics */
    unsigned int __total_received_bytes;    ///< Total amount of bytes received
    unsigned int __total_received_packets;  ///< Total number of packets received
    unsigned int __total_discarded_packets; ///< Total number of packets discarded
    unsigned int __total_lost_packets;      ///< Total number of packets lost
    /* End< */
  };
  
}

#include "nmm/nmm_suffix.hpp"

#endif
