//---------------------------------------------------------------------------
//
// 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  |
// -----+--------+------------------------------------------+------+---------
//---------------------------------------------------------------------------

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

#include "seminole.h"
#include "sem_template.h"

#include "sitedata.h"

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

struct UserAccount
{
  char            mUserName[32];
  const char     *mpRole;
  long            mFailedLogins;
  unsigned long   mUniqueId;
  bool            mLoggedIn;
};

class DemoHandler : public HttpdFileHandler
{
protected:
  void SendFile(RequestState &state);
    
public:
  DemoHandler(HttpdFileSystem *p_filesys,
              const char      *p_root,
              const char      *p_prefix);
};

class DemoSymbolTable : public HttpdSymbolTable
{
  bool   mLast;

public:
  DemoSymbolTable() : mLast(false) {}

  virtual int HandleCond(HttpdConditionalCommand *p_cond);
  virtual int HandleLoop(HttpdLoopCommand *p_loop);
};

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

static const HttpdSymbolEntry gUserAccountMap[] =
{
  {
    "id",                                 // Symbol name
    offsetof(UserAccount, mUniqueId),     // Offset of field
    HttpdSymbolMap::EvalHexUlong,         // Eval callback
    NULL,                                 // Loop callback
    NULL                                  // Conditional callback
  },

  {
    "login-fail",                         // Symbol name
    offsetof(UserAccount, mFailedLogins), // Offset of field
    HttpdSymbolMap::EvalLong,             // Eval callback
    NULL,                                 // Loop callback
    NULL                                  // Conditional callback
  },

  { 
    "name",                               // Symbol name
    offsetof(UserAccount, mUserName),     // Offset of field
    HttpdSymbolMap::EvalStringBuffer,     // Eval callback
    NULL,                                 // Loop callback
    NULL                                  // Conditional callback
  },

  {
    "online",                             // Symbol name
    offsetof(UserAccount, mLoggedIn),     // Offset of field
    NULL,                                 // Eval callback
    NULL,                                 // Loop callback
    HttpdSymbolMap::CondBool              // Conditional callback
  },

  {
    "role",                               // Symbol name
    offsetof(UserAccount, mpRole),        // Offset of field
    HttpdSymbolMap::EvalString,           // Eval callback
    NULL,                                 // Loop callback
    NULL                                  // Conditional callback
  }
};

static const UserAccount gAccounts[] =
{
  // Name       Role              F.Count   Unique Id    Logged In
  {  "sam",     "administrator",  2,        0x0badd00d,  true    },
  {  "fred",    "user",           0,        0x0000001f,  false   },
  {  "bob",     "user",           0,        0x00000002,  false   },
  {  "david",   "user",           1,        0x0000009b,  true    },
  {  "moshe",   "administrator",  0,        0xbeefd00d,  false   },
  {  "sally",   "user",           0,        0x00000103,  false   },
  {  "patty",   "user",           0,        0x0000010d,  true    }
};

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

//---------------------------------------------------------------------------
//
// NAME:           DemoHandler::DemoHandler
//
// DESCRIPTION:    Construct the request handler.
//
// AUTHOR:         M. Grosberg
// CREATED:        May 25, 2006
// LAST MODIFIED:  N/A           BY:  N/A
//
//--------------------------------------------------------------------------
DemoHandler::DemoHandler
 (
   HttpdFileSystem *p_filesys,
   const char      *p_root,
   const char      *p_prefix
 )
 : HttpdFileHandler(p_filesys, p_root, p_prefix)
{}

//---------------------------------------------------------------------------
//
// NAME:           DemoSymbolTable::HandleLoop
//
// DESCRIPTION:    Handle looping requests in our symbol table.
//
// RETURNS:        Status code.
//
// AUTHOR:         M. Grosberg
// CREATED:        May 25, 2006
// LAST MODIFIED:  N/A           BY:  N/A
//
//--------------------------------------------------------------------------
int DemoSymbolTable::HandleLoop(HttpdLoopCommand *p_loop)
{
  if (strcmp(p_loop->Name(), "accounts") == 0)
  {
    for(size_t i = 0; i < HTTPD_NUMELEM(gAccounts); i++)
    {
      // Allocate a new scope and populate it with the symbol map
      // of this account. Further loops can create more nested scopes
      // if desired.
      HttpdScopedSymbolMap ssmap(p_loop->Processor(),
                                 gUserAccountMap,
                                 HTTPD_NUMELEM(gUserAccountMap),
                                 gAccounts + i);

      mLast = (i == (HTTPD_NUMELEM(gAccounts) - 1));
      if (p_loop->Iterate() != 0)
        break;
    }

    mLast = false;
    return (0);
  }

  return (HTTPD_TEMPLATE_NOT_HANDLED);
}

//---------------------------------------------------------------------------
//
// NAME:           DemoSymbolTable::HandleCond
//
// DESCRIPTION:    Handle conditional requests in our symbol table.
//
// RETURNS:        Status code.
//
// AUTHOR:         M. Grosberg
// CREATED:        May 25, 2006
// LAST MODIFIED:  N/A           BY:  N/A
//
//--------------------------------------------------------------------------
int DemoSymbolTable::HandleCond(HttpdConditionalCommand *p_cond)
{
  if (strcmp(p_cond->Name(), "last") == 0)
    return (ReturnBool(mLast));
  else
    return (HTTPD_TEMPLATE_NOT_HANDLED);
}

//---------------------------------------------------------------------------
//
// NAME:           DemoHandler::SendFile
//
// DESCRIPTION:    Handle template file processing if a file to be sent
//                 needs template expansion.
//
// REMARKS:        This is the most common way of hooking the template
//                 engine and file handler together. This allows normal
//                 processing for any file except for templates which
//                 share a special MIME type.
//
// AUTHOR:         M. Grosberg
// CREATED:        May 25, 2006
// LAST MODIFIED:  N/A           BY:  N/A
//
//--------------------------------------------------------------------------
void DemoHandler::SendFile(RequestState &state)
{
  if (strcmp(state.mFileInfo.MimeType(), "x-server-internal/template") == 0)
  {
    DemoSymbolTable  dst;
    (void )HttpdFSTemplateShell::Execute(state, &dst);
  }
  else
    HttpdFileHandler::SendFile(state);
}

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

//---------------------------------------------------------------------------
//
// 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 DemoHandler hand(&romfs, "/", "/");
  gpWebServer->Install(&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);
}
