/**
 * @file
 * $Id$
 * $Revision$
 * $Author$
 * $Date$
 *
 * This file is part of The iWear Framework.
 *
 * The iWear Framework 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 as in version 2 of the License.

 * 
 * The iWear Framework 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
 * The iWear Framework; if not, write to the Free Software Foundation, Inc., 59
 * Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#ifndef __IWEAR_UDPCONNECTION_H
#define __IWEAR_UDPCONNECTION_H

#ifndef __IWEAR_IPCONNECTION_H
#include <net/ipconnection.h>
#endif

#ifndef __IWEAR_PACKETCONNECTION_H
#include <net/packetconnection.h>
#endif

#include <queue>
#include <map>
using std::queue;
using std::map;

namespace iwear
{
    namespace net
    {
class UDPConnection : public IPConnection, public PacketConnection
{
private:
protected:

union sockaddr_u {
    struct sockaddr sa;
    struct sockaddr_in in;
    struct sockaddr_in6 in6;
    bool operator==( const sockaddr_u& a ) const
    {
	return (memcmp(&a,this,sizeof(a)) == 0 );
    }
    bool operator!=(const sockaddr_u& a ) const
    {
	return !( *this == a );
    }

    bool operator<( const sockaddr_u& a ) const
    {
	return (memcmp(&a,this,sizeof(a)) < 0 );
    }
};
    sockaddr_u myaddr;
    UDPConnection* master;
    void queue_packet( const sockaddr_u& frm, const char* buf );
    map<sockaddr_u, queue<const char*> > p_queues;
    map<sockaddr_u, queue<const char*> > w_queues;
    queue<sockaddr_u> w_q;

    /**
     * read a bit of data into the queue.
     */
    void read_into_queue( void );
public:
    virtual bool is_connected( void ) { return (fd > 0); }

    UDPConnection( ip_version ipv = IPv6, block_mode bm = blocking, int prot = 0);
    
    virtual ~UDPConnection();
    
    static UDPConnection* create( const IPAddress& ip, block_mode bm = non_blocking );
    
    virtual ssize_t read( void * buf, size_t count, float to = DEFAULT_TIMEOUT, bool check = true );

    virtual string read( size_t count, float to = DEFAULT_TIMEOUT, bool check = true);

    virtual ssize_t write( const void * buf , size_t count, float to = DEFAULT_TIMEOUT, bool check = true );

    virtual ssize_t write( const string& dat, string::size_type pos = 0, float to = DEFAULT_TIMEOUT, bool check =true );
    
    virtual void reconnect( float to = DEFAULT_TIMEOUT );

    virtual UDPConnection* accept( float to = DEFAULT_TIMEOUT, bool checkfd = true );
};

}
}

#endif
