/*  This is the interface to the simple HTTP server and client used for inter-process communication.

    *** This should only be used within libxm. It is subject to change without notice. ***
    
    @author  J. Czechowski IV
    @since   NeXtMidas 2.1.2
*/

#ifndef _HttpConnection
#define _HttpConnection

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>

#define MAX_REQUESTS 5 /* Maximum number of requests to listen for. */

#define FALSE 0
#define TRUE  1

typedef struct sockaddr_in socket_addr_t;

typedef struct {
  int   numRead;   /* Number of bytes read */
  int   status;    /* HTTP status (200, 404, etc) */
  int   length;    /* Content length (-1=Unknown) */
  int   dataStart; /* Data start index into the buffer */
} http_info_t;


typedef struct server_info_struct {
  int   port;      /* Port being used. */
  int   stop;      /* Should the server be stopped? */
  int   sd;        /* Socket descriptor for the server socket (<0 invalid). */
  pid_t pid;       /* PID of the server processing loop (0=SingleThread). */
  void* userData;  /* User data that may be used by childProcess (ignored by server). */
  
  struct sockaddr_in servAddr; /* Server address. */
  
  /* Function pointer to the function to process the request. The function should have the
     signature "int func(server_info_t* serverInfo, int sock, socket_addr_t* addr)" and
     should return TRUE if the server should keep running, FALSE if it should stop.
     (Note: The socket will be closed after the method returns.)
  */
  int (*requestHandler)(struct server_info_struct*,int,socket_addr_t*);
  
  /* Function pointer to the child process to start (NULL if none). The function should have
     the signature "int func(server_info_t* serverInfo)" and should return TRUE if the server
     should keep running, FALSE if it should stop.
  */
  int (*childProcess)(struct server_info_struct*);

} server_info_t;


/** Do an HTTP GET request.
    @param hostname The host name (e.g. "nextmidas.com").
    @param port     The host prot (e.g. 80).
    @param path     The host path (e.g. "/nextmidas/"), must be at least "/".
    @param buffer   Output buffer.
    @param lbuffer  Length of output buffer.
    @param httpInfo HTTP output info from the request (NULL if not interested).
 */
int httpGet(char* hostname, int port, char* path, char* buffer, int lbuffer, http_info_t *httpInfo);



/** Starts the server. Note that serverInfo.requestHandler and serverInfo.childProcess must be set
    before this method is called (serverInfo.childProcess can be NULL).
    @param firstPort  First port to try.
    @param lastPort   Last port to try. (If firstPort==lastPort then only one port number is used.)
    @param serverInfo Info about the server.
    @return TRUE on success, FALSE on failure.
 */
int runHttpServer(int firstPort, int lastPort, server_info_t* serverInfo);


#endif /* _HttpConnection */
