// ---------------------------------------------------------------------------
// - HttpResponse.cpp                                                        -
// - afnix:nwg module - http response class implementation                   -
// ---------------------------------------------------------------------------
// - This program is free software;  you can redistribute it  and/or  modify -
// - it provided that this copyright notice is kept intact.                  -
// -                                                                         -
// - This program  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.  In no event shall -
// - the copyright holder be liable for any  direct, indirect, incidental or -
// - special damages arising in any way out of the use of this software.     -
// ---------------------------------------------------------------------------
// - copyright (c) 1999-2009 amaury darsch                                   -
// ---------------------------------------------------------------------------

#include "Regex.hpp"
#include "Vector.hpp"
#include "Boolean.hpp"
#include "Integer.hpp"
#include "Utility.hpp"
#include "Runnable.hpp"
#include "QuarkZone.hpp"
#include "Exception.hpp"
#include "InputBound.hpp"
#include "HttpResponse.hpp"

namespace afnix {

  // -------------------------------------------------------------------------
  // - private section                                                       -
  // -------------------------------------------------------------------------
  
  // the http status code
  static const long HTTP_STAT_200 = 200; // OK
  static const long HTTP_STAT_201 = 201; // Created
  static const long HTTP_STAT_301 = 301; // Move Permanently
  static const long HTTP_STAT_302 = 302; // Found
  static const long HTTP_STAT_303 = 303; // See Other

  /// the status line regex
  static const String HTTP_RESP_RGEX = "(HTTP/$d.$d)$b+($d+)$b+$N+";
  /// the content length property
  static const String HTTP_HEAD_CLEN = "Content-Length";
  /// the content type property
  static const String HTTP_HEAD_CTYP = "Content-Type";
  /// the location property
  static const String HTTP_HEAD_HLOC = "Location";
  // the http cookie version 0 name
  static const String HTTP_HEAD_COK0 = "Set-Cookie";
  // the http cookie version 1 name
  static const String HTTP_HEAD_COK1 = "Set-Cookie2";
  /// the media type regex
  static const String HTTP_MIME_RGEX = "(<$a-+>+/<$a-+>+)[;$N+]?";
  /// the default http media type
  static const String HTTP_MIME_MDEF = "text/plain";
  /// the charset regex
  static const String HTTP_CHAR_RGEX = "$N+charset=(<$a->+)";
  /// the default http charset
  static const String HTTP_CHAR_CDEF = "DEFAULT";

  // this procedure returns the response status line
  static String http_status_line (InputStream& is, long& code) {
    // check for valid stream
    if (is.valid () == false) {
      throw Exception ("http-error", "http status timeout");
    }
    // get the status line
    String line = is.readln ();
    Regex    re = HTTP_RESP_RGEX;
    if (re == line) {
      String vers = re.getstr (0);
      String data = re.getstr (1);
      code = Utility::tointeger (data);
      return vers;
    }
    throw Exception ("http-error", "invalid http status line", line);
  }

  // this procedure extract the media type from the header
  static String http_get_media (const Plist& head) {
    // check for the content type property
    if (head.exists (HTTP_HEAD_CTYP) == false) {
      throw Exception ("http-error", "media type is not defined in header");
    }
    // get the content type property
    String pval = head.getpval (HTTP_HEAD_CTYP);
    // extract the content value
    Regex re = HTTP_MIME_RGEX;
    if (re == pval) return re.getstr (0);
    throw Exception ("http-error", "cannot extract media type", pval);
  }

  // this procedure returns true if the encoding mode is defined in the header
  static bool http_is_emod (const Plist& head) {
    // check for the content type property
    if (head.exists (HTTP_HEAD_CTYP) == true) {
      // get the content type property
      String pval = head.getpval (HTTP_HEAD_CTYP);
      // extract the content value
      Regex re = HTTP_CHAR_RGEX;
      return (re == pval);
    }
    // not defined
    return false;
  }

  // this procedure extract the character set from the header
  static String http_get_emod (const Plist& head) {
    // check for the content type property
    if (head.exists (HTTP_HEAD_CTYP) == true) {
      // get the content type property
      String pval = head.getpval (HTTP_HEAD_CTYP);
      // extract the content value
      Regex re = HTTP_CHAR_RGEX;
      if (re == pval) return re.getstr (0);
    }
    // by default we operate in byte mode
    return HTTP_CHAR_CDEF;
  }

  // return the header response content length
  static long http_get_length (const Plist& head) {
    // check for a content lenth property
    if (head.exists (HTTP_HEAD_CLEN) == true) {
      // get the content length property
      String pval = head.getpval (HTTP_HEAD_CLEN);
      // convert to an integer
      return Utility::tointeger(pval);
    }
    // no length specified
    return 0;
  }

  // -------------------------------------------------------------------------
  // - class section                                                         -
  // -------------------------------------------------------------------------
  
  // create a default response

  HttpResponse::HttpResponse (void) {
    reset ();
  }

  // create a http response by status code

  HttpResponse::HttpResponse (const long code) {
    // reset protocol
    reset ();
    // set the status code
    d_code = code;
  }

  // create a http response by status code and type

  HttpResponse::HttpResponse (const long code, const String& type) {
    // reset protocol
    reset ();
    // set the status code
    d_code = code;
    // add the content-type property
    hset (HTTP_HEAD_CTYP, type);  
  }
    
  // create a http response by input stream
  
  HttpResponse::HttpResponse (InputStream& is){
    parse (is);
  }
  
  // return the class name

  String HttpResponse::repr (void) const {
    return "HttpResponse";
  }
  
  // reset the response and reset

  void HttpResponse::reset (void) {
    wrlock ();
    try {
      HttpProto::reset ();
      d_code = 0;
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // parse the response input stream

  void HttpResponse::parse (InputStream& is) {
    wrlock ();
    try {
      // reset everything
      reset ();
      // get the status version
      String vers = http_status_line (is, d_code);
      setvers (vers);
      // read the header
      hparse (is);
      // unlock and return
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }
			       
  // write the http response to an output stream
  
  void HttpResponse::write (OutputStream& os) const {
    rdlock ();
    try {
      // write the response
      String rsta = d_vers + ' ' + HttpProto::mapcode (d_code);
      os.writeln (rsta, true);
      // write the header
      HttpProto::write (os);
      // done
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }
  
  // write the http request to a buffer
  
  void HttpResponse::write (Buffer& buf) const {
    rdlock ();
    try {
      // write the response
      String rsta = d_vers + ' ' + HttpProto::mapcode (d_code);
      buf.add (rsta);
      buf.add (crlq);
      buf.add (eolq);
      // write the header
      HttpProto::write (buf);
      // done
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  InputStream* HttpResponse::getris (InputStream* is) const {
    rdlock ();
    try {
      // check fo an ok status
      if (isok () == false) {
	unlock ();
	return nilp;
      }
      // get the content length
      long clen= http_get_length (d_head);
      // create a input bounded stream
      InputBound* result = new InputBound (is, clen);
      // set the encoding mode if any
      if (http_is_emod (d_head) == true) {
	result->setemod (http_get_emod (d_head));
      }
      // here it is
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return true if the status code is ok

  bool HttpResponse::isok (void) const {
    rdlock ();
    try {
      bool status = (d_code == HTTP_STAT_200);
      unlock ();
      return status;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // set the response status by code

  void HttpResponse::setstatus (const long code) {
    wrlock ();
    try {
      d_code = code;
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return the status code

  long HttpResponse::getstatus (void) const {
    rdlock ();
    try {
      long result = d_code;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    } 
  }

  // return true if the media type is defined

  bool HttpResponse::ismedia (void) const {
    rdlock ();
    try {
      bool result = d_head.exists (HTTP_HEAD_CTYP);
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return the media type

  String HttpResponse::getmedia (void) const {
    rdlock ();
    try {
      String result = http_get_media (d_head);
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return true if the encoding mode is defined in the header

  bool HttpResponse::isemod (void) const {
    rdlock ();
    try {
      bool result = http_is_emod (d_head);
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return the content encoding mode if any

  String HttpResponse::getemod (void) const {
    rdlock ();
    try {
      String result = http_get_emod (d_head);
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return true if there is something at another location

  bool HttpResponse::ishloc (void) const {
    rdlock ();
    try {
      // check first for a location property
      if (hexists (HTTP_HEAD_HLOC) == false) {
	unlock ();
	return false;
      }
      // check the status code
      bool status = false;
      switch (d_code) {
      case HTTP_STAT_201:
      case HTTP_STAT_301:
      case HTTP_STAT_302:
      case HTTP_STAT_303:
	status = true;
	break;
      default:
	status = false;
	break;
      }
      unlock ();
      return status;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // set a header location as a redirect

  void HttpResponse::sethloc (const String& uri) {
    wrlock ();
    try {
      // set a status 303 (see other)
      setstatus (303);
      // set the redirection location
      hset (HTTP_HEAD_HLOC, uri);
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return the header location value

  String HttpResponse::gethloc (void) const {
    rdlock ();
    try {
      String result = hmap (HTTP_HEAD_HLOC);
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // set a cookie in the response header

  void HttpResponse::setcookie (const Cookie& cook) {
    wrlock ();
    try {
      if (cook.getvers () == 0) {
	hset (HTTP_HEAD_COK0, cook.tostring ());
      } else if (cook.getvers () == 1) {
	hset (HTTP_HEAD_COK1, cook.tostring ());
      } else {
	throw Exception ("http-error", "invalid cookie version");
      }
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // -------------------------------------------------------------------------
  // - object section                                                        -
  // -------------------------------------------------------------------------
  
  // the quark zone
  static const long QUARK_ZONE_LENGTH = 12;
  static QuarkZone  zone (QUARK_ZONE_LENGTH);
  
  // the object supported quarks
  static const long QUARK_OKP      = zone.intern ("status-ok-p");
  static const long QUARK_HLOCP    = zone.intern ("location-p");
  static const long QUARK_EMODP    = zone.intern ("encoding-mode-p");
  static const long QUARK_GETRIS   = zone.intern ("get-response-stream");
  static const long QUARK_MEDIAP   = zone.intern ("media-type-p");
  static const long QUARK_GETEMOD  = zone.intern ("get-encoding-mode");
  static const long QUARK_SETCODE  = zone.intern ("set-status-code");
  static const long QUARK_GETCODE  = zone.intern ("get-status-code");
  static const long QUARK_GETHLOC  = zone.intern ("get-location");
  static const long QUARK_SETHLOC  = zone.intern ("set-location");
  static const long QUARK_SETCOOK  = zone.intern ("set-cookie");
  static const long QUARK_GETMEDIA = zone.intern ("get-media-type");
  
  // create a new object in a generic way
  
  Object* HttpResponse::mknew (Vector* argv) {
    long argc = (argv == nilp) ? 0 : argv->length ();
    // check for 0 argument
    if (argc == 0) return new HttpResponse;
    // check for 1 argument
    if (argc == 1) {
      Object* obj = argv->get (0);
      // check for an integer
      Integer* iobj = dynamic_cast <Integer*> (obj);
      if (iobj != nilp) {
	long code = iobj->tointeger ();
	return new HttpResponse (code);
      }
      // check for an input stream
      InputStream* is = dynamic_cast <InputStream*> (obj);
      if (is != nilp) return new HttpResponse (*is);
      // invalid arguments
      throw Exception ("type-error", 
		       "invalid object for http response constructor",
		       Object::repr (obj));
    }
    // check for 2 arguments
    if (argc == 2) {
      long   code = argv->getint (0);
      String type = argv->getstring (1);
      return new HttpResponse (code, type);
    }
    throw Exception ("argument-error", 
		     "too many arguments with http response constructor");
  }

  // return true if the given quark is defined
  
  bool HttpResponse::isquark (const long quark, const bool hflg) const {
    rdlock ();
    if (zone.exists (quark) == true) {
      unlock ();
      return true;
    }
    bool result = hflg ? HttpProto::isquark (quark, hflg) : false;
    unlock ();
    return result;
  }
  
  // apply this object with a set of arguments and a quark
  
  Object* HttpResponse::apply (Runnable* robj, Nameset* nset, const long quark,
			       Vector* argv) {
    // get the number of arguments
    long argc = (argv == nilp) ? 0 : argv->length ();
    
    // dispatch 0 argument
    if (argc == 0) {
      if (quark == QUARK_OKP)      return new Boolean (isok      ());
      if (quark == QUARK_HLOCP)    return new Boolean (ishloc    ());
      if (quark == QUARK_EMODP)    return new Boolean (isemod    ());
      if (quark == QUARK_MEDIAP)   return new Boolean (ismedia   ());
      if (quark == QUARK_GETEMOD)  return new String  (getemod   ());
      if (quark == QUARK_GETCODE)  return new Integer (getstatus ());
      if (quark == QUARK_GETHLOC)  return new String  (gethloc   ());
      if (quark == QUARK_GETMEDIA) return new String  (getmedia  ());
    }
    // dispatch 1 argument
    if (argc == 1) {
      if (quark == QUARK_SETCODE) {
	long code = argv->getint (0);
	setstatus (code);
	return nilp;
      }
      if (quark == QUARK_SETHLOC) {
	String uri = argv->getstring (0);
	sethloc (uri);
	return nilp;
      }
      if (quark == QUARK_GETRIS) {
	Object* obj = argv->get (0);
	InputStream* is = dynamic_cast <InputStream*> (obj);
	if (is == nilp) {
	  throw Exception ("type-error", 
			   "invalid object as a result input stream",
			   Object::repr (obj));
	}
	return getris (is);
      }
      if (quark == QUARK_SETCOOK) {
        Object*   obj = argv->get (0);
        Cookie*  cobj = dynamic_cast <Cookie*> (obj);
        if (cobj == nilp) {
          throw Exception ("type-error", "invalid object with set-cookie",
                           Object::repr (obj));
        }
	setcookie (*cobj);
	return nilp;
      }
    }
    // call the http proto method
    return HttpProto::apply (robj, nset, quark, argv);
  }
}
