#ifndef n_ServerPush_H_
#define n_ServerPush_H_

/*
 *
 * nucleo/network/http/ServerPush.H --
 *
 * Copyright (C) Nicolas Roussel
 *
 * See the file LICENSE for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 */

#include <sys/uio.h>
#include <sys/errno.h>

#include <unistd.h>
#include <stdio.h>

#include <stdexcept>

namespace nucleo {

  // ------------------------------------------------------------------

  class ServerPush {

  private:

    int _fd ;

  public:

    ServerPush(int fd) {
	 _fd = fd ;

	 char buffer[512] ;
#if 1
	 sprintf(buffer,"HTTP/1.0 200 OK\r\nCache-Control: no-cache\r\nContent-type: multipart/x-mixed-replace;boundary=-nUcLeO->\r\nConnexion: keep-alive\r\n\r\n-nUcLeO->\r\n") ;
#else
	 sprintf(buffer,"HTTP/1.0 200 OK\r\nCache-Control: no-cache\r\nContent-type: multipart/x-mixed-replace;boundary=-nUcLeO->\r\nConnexion: keep-alive\r\n\r\n") ;
#endif
	 if (write(_fd, buffer, strlen(buffer))==-1) throw std::runtime_error("ServerPush: write failed") ;
    }

    void
    push(const char *content_type, char *content, int content_length, const char *headers=0) {
	 char buffer[512] ;
	 if (headers)
	   sprintf(buffer, "%s\r\nContent-Type: %s\r\nContent-Length: %d\r\n\r\n",
			 headers, content_type, content_length) ; 
	 else
	   sprintf(buffer, "Content-Type: %s\r\nContent-Length: %d\r\n\r\n",
			 content_type, content_length) ; 
	 struct iovec iov[3] ;   
	 iov[0].iov_base = buffer ;
	 iov[0].iov_len = strlen(buffer) ;
	 iov[1].iov_base = content ;
	 iov[1].iov_len = content_length ;
	 iov[2].iov_base = (char *)"\r\n-nUcLeO->\r\n" ;
	 iov[2].iov_len = 13 ;
	 if (writev(_fd, iov, 3)==-1) throw std::runtime_error("ServerPush::push: writev failed") ;
    }

  } ;

  // ------------------------------------------------------------------

}

#endif
