//---------------------------------------------------------------------------
//
// MODULE NAME:     main.cpp
//
// COPYRIGHT:       Copyright (c) 2013, GladeSoft, Inc.
//                  All Rights Reserved.
//
//                  NOTICE: THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF
//                  GLADESOFT, INC., AND SHALL NOT BE REPRODUCED, COPIED
//                  IN WHOLE OR IN PART ADAPTED, MODIFIED, OR
//                  DISSEMINATED WITHOUT THE EXPRESS WRITTEN CONSENT
//                  OF GLADESOFT, INC. ANY REDISTRIBUTION OR
//                  PUBLICATION TO UNAUTHORIZED PERSONS IS STRICTLY
//                  PROHIBITED BY U.S. AND INTERNATIONAL COPYRIGHT LAW.
//
// DESCRIPTION:     Another example program using the Seminole embedded 
//                  web server.
//
// AUTHOR:          S. Conner
//
// CREATION DATE:   Mar  5, 2004
//
//---------------------------------------------------------------------------
//
// HISTORY OF CHANGE  
//
// -----+--------+------------------------------------------+------+---------
// VERS | DATE   | DESCRIPTION OF CHANGE                    | INIT | PR#
// =====+========+==========================================+======+=========
//  001 |03/05/04| File creation.                           | SPC  |
// -----+--------+------------------------------------------+------+---------
//  002 |06/12/09| Const correctness.                       | RAH  |
//      |        | Add file handler to serve up main FORM   |      |
// -----+--------+------------------------------------------+------+---------
//---------------------------------------------------------------------------

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

#include "seminole.h"
#include "sitedata.h"

//**********************************************************************

class DemoCgiHandler : public HttpdHandler
{
public:
  DemoCgiHandler(const char *p_prefix);
  virtual ~DemoCgiHandler();
  virtual bool Handle(HttpdRequest *p_req);
};

static const char  gServername[] = "localhost";
static const int   gServerport   = 8080;
static Httpd      *gpWebServer;

//**********************************************************************

//---------------------------------------------------------------------------
//
// NAME:           DemoCgiHandler::DemoCgiHandler
//
// DESCRIPTION:    Construct the demo request handler.
//
// AUTHOR:         S. Conner
// CREATED:        Mar  6, 2004
// LAST MODIFIED:  N/A           BY:  N/A
//
//--------------------------------------------------------------------------
DemoCgiHandler::DemoCgiHandler(const char *p_prefix)
{
  mpPrefix = HttpdUtilities::SaveString(p_prefix);
}

//---------------------------------------------------------------------------
//
// NAME:           DemoCgiHandler::~DemoCgiHandler
//
// DESCRIPTION:    Destroy the demo request handler.
//
// AUTHOR:         S. Conner
// CREATED:        Mar  6, 2004
// LAST MODIFIED:  N/A           BY:  N/A
//
//--------------------------------------------------------------------------
DemoCgiHandler::~DemoCgiHandler()
{
#if HTTPD_INC_SHUTDOWN
  HttpdOpSys::Free((char *)mpPrefix);
#endif
}

//---------------------------------------------------------------------------
//
// NAME:           DemoCgiHandler::Handle
//
// DESCRIPTION:    Process the request.
//
// RETURNS:        True if the request was handled by this handler,
//                 false if no processing has been performed.
//
// AUTHOR:         S. Conner
// CREATED:        Mar  6, 2004
// LAST MODIFIED:  N/A           BY:  N/A
//
//--------------------------------------------------------------------------
bool DemoCgiHandler::Handle(HttpdRequest *p_req)
{
  assert(p_req != NULL);
  
  if (IsMe(p_req))
  {
    //-------------------------------------------------------
    // we only accept POST methods in this handler, which is
    // the most common method of handling HTML forms.
    //-------------------------------------------------------

    if (!p_req->IsPostRequest())
    {
      p_req->Respond(HTTPD_RESP_METHOD_NOT_ALLOWED);
      return (true);
    }
    
    //----------------------------------------------------------
    // This call collects the parameters into an array for us
    // to use.  If there is no Content-type passed in, or it's of
    // the wrong type, then HttpdCgiParameter::ParsePostData()
    // will return NULL.
    //----------------------------------------------------------
    
    HttpdCgiParameter *p_list = HttpdCgiParameter::ParsePostData(p_req);
    if (p_list == NULL)
    {
      p_req->Respond(HTTPD_RESP_SRV_ERROR);
      return (true);
    }
  
    //---------------------------------------------------------
    // We accept three parameters, "name", "title" and "age".  
    // We don't do much with the data, other than print it out,
    // but this is the basics of getting CGI data from the client.
    //------------------------------------------------------------

    HttpdDynamicOutput output(p_req, false);
    p_req->Respond(HTTPD_RESP_OK);
    
    const char *p_name  = p_list->Find("name");
    const char *p_title = p_list->Find("title");
    const char *p_age   = p_list->Find("age");
    
    output.Header("Content-Type", "text/plain");
    output.HeaderComplete();
    
    output.Body()->Printf(
                           "Name:  %s\r\n"
                           "Title: %s\r\n"
                           "Age:   %s\r\n",
                           p_name  ? p_name  : "none given",
                           p_title ? p_title : "none given",
                           p_age   ? p_age   : "none given"
                         );

    HttpdCgiParameter::FreeList(p_list);
    return (true);
  }
  
  return (false);
}

//***********************************************************************

//---------------------------------------------------------------------------
//
// NAME:           failure
//
// DESCRIPTION:    Handle a fatal error.
//
// AUTHOR:         S. Conner
// CREATED:        Mar  6, 2004
// LAST MODIFIED:  N/A           BY:  N/A
//
//--------------------------------------------------------------------------
static void failure(const char *p_file, int line, const char *p_msg)
{
  assert(p_file != NULL);
  assert(line   >  0);
  assert(p_msg  != NULL);
  
  fprintf(stderr, "%s:%d Call to %s failed\n", p_file, line, p_msg);
  exit(EXIT_FAILURE);
}

//---------------------------------------------------------------------------
//
// NAME:           Initialize_The_Web_Server
//
// DESCRIPTION:    Start and configure Seminole.
//
// AUTHOR:         S. Conner
// CREATED:        Mar  6, 2004
// LAST MODIFIED:  N/A           BY:  N/A
//
//--------------------------------------------------------------------------
static void Initialize_The_Web_Server()
{
  //-------------------------------------------------------
  // Initialize the environment.
  //-------------------------------------------------------
  
  if (Httpd::Init() != 0)
    failure(__FILE__, __LINE__, "Httpd::Init()");
  
  //--------------------------------------------------------
  // Create the webserver instance.  This just initializes
  // the object --- it doesn't start it up.
  //--------------------------------------------------------
    
  gpWebServer = new Httpd(gServername, gServerport);
  if (gpWebServer == NULL)
    failure(__FILE__, __LINE__, "Httpd::Httpd()");

  static HttpdMemoryDataSource builtin(SemWeb, sizeof(SemWeb));
  static HttpdRomFileSystem    romfs;
  if (romfs.Mount(&builtin) != 0)
    failure(__FILE__, __LINE__, "HttpdRomFileSystem::Mount()");

  static HttpdFileHandler file_hand(&romfs, "/", "/");
  gpWebServer->Install(&file_hand);

  static DemoCgiHandler demo_hand("/sample.cgi");
  gpWebServer->Install(&demo_hand);

  printf("Server started on host %s port %d\n", gServername, gServerport);
}

//---------------------------------------------------------------------------
//
// NAME:           main
//
// DESCRIPTION:    Entry point for the demo.
//
// AUTHOR:         S. Conner
// CREATED:        Mar  6, 2004
// LAST MODIFIED:  N/A           BY:  N/A
//
//--------------------------------------------------------------------------
int main(int argc, const char *const *argv)
{
  char buf[4];

  Initialize_The_Web_Server();
  gpWebServer->Start();
  
  printf("Press <ENTER> to stop.\n");
  fgets(buf, sizeof(buf), stdin);
  
#if HTTPD_INC_SHUTDOWN
  gpWebServer->Stop(HARD);
#endif

  return (EXIT_SUCCESS);
}
