#ifndef __TCPSERVER_H__
#define __TCPSERVER_H__

#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h> 
#include <stdlib.h>    
#include <string>    
#include <unistd.h>
#include "tcpconnection.h"
#include <iostream>
#include <sys/select.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/types.h>

/// server will listen on loop back
class tcpserver
{
 public:
  tcpserver();
  ~tcpserver();

  /// initialize
  /**
   * @param ip ip address to listen to
   * @param port to listen to
   */
  int init( std::string ip, int port );

  /// wait for connection
  /**
   * wait for connection and initialize the connection object
   * 
   * wait time out is 5 seconds
   * @param tc connection object
   * @return -1 on timeout or error
   */
  int wait( tcpconnection &tc );

  /// closes socket
  int closesocket();

 private:
  struct sockaddr_in address;
  int ready;       ///< ready flag
  int sock;        ///< connection socket
  std::string ip;  ///< listen ip
  int port;        ///< listen port
  fd_set fdset;
};

#endif
