/*

   SysopChat Door
   ==============

   functions of door.

   - doorname MUST be "SysopChat"
   - display "ChatStart" screen
   - chat to user until DOOR_GetLine() returns IN_ENDCHAT or user loses carrier
   - display "ChatEnd" screen

*/


#include <exec/types.h>
#include <exec/memory.h>
#include <dos/dos.h>
#include <clib/exec_protos.h>
#include <clib/dos_protos.h>
#include <clib/alib_protos.h>

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <time.h>


#ifdef __SASC
int CXBRK(void) { return(0); }
int _CXBRK(void) { return(0); }
void chkabort(void) {}
#endif

#include <HBBS/ANSI_Codes.h>
#include <HBBS/Defines.h>
#include <HBBS/types.h>
#include <HBBS/structures.h>
#include <HBBS/hbbscommon_protos.h>
#include <HBBS/hbbscommon_pragmas.h>
#include <HBBS/Hbbsnode_protos.h>
#include <HBBS/Hbbsnode_pragmas.h>
#include <HBBS/release.h>
char *versionstr="$VER: SysopChat "RELEASE_STR;

struct Library *HBBSCommonBase=NULL;
struct Library *HBBSNodeBase=NULL;

struct BBSGlobalData *BBSGlobal=NULL;
struct NodeData *N_ND=NULL;
int N_NodeNum=-1;

static VOID cleanup(ULONG num)
{
  if (HBBSNodeBase)
  {
    HBBS_CleanUpDoor();
    CloseLibrary (HBBSNodeBase);
  }

  if (HBBSCommonBase)
  {
    HBBS_CleanUpCommon();
    CloseLibrary (HBBSCommonBase);
  }

  if (num) printf("Door Error = %d\n",num);

  exit(0);
}

static VOID init(char *name)
{
  if(!(HBBSCommonBase = OpenLibrary("HBBSCommon.library",0)))
  {
    cleanup(1);
  }

  if (!(HBBS_InitCommon()))
  {
    cleanup(2);
  }

  if(!(HBBSNodeBase = OpenLibrary("HBBSNode.library",0)))
  {
    cleanup(3);
  }

  if (!(HBBS_InitDoor(N_NodeNum,name)))
  {
    cleanup(4);
  }
  SetProgramName(name);
}

void DoChat( void )
{
  BOOL Done=FALSE;
  char linewrap[BIG_STR]="";

  do
  {
    switch( DOOR_GetLine(GL_HISTORY|GL_EDIT|GL_DISPLAY|GL_LINEWRAP|GL_IMMEDIATE,'\0',78,0,linewrap) )
    {
      case IN_ENDCHAT:
      case IN_LOSSCARRIER:
        Done=TRUE;
        break;
      case IN_GOTLINE:
        if (stricmp("ENDCHAT",N_ND->CurrentLine)==0) Done=TRUE;
        break;
    }
    strcpy(linewrap,N_ND->CurrentLineWrap);
  } while (!Done && N_ND->OnlineStatus==OS_ONLINE);
}

void DoorMain(int argc,char *argv[])
{

  DOOR_WriteText("\r\n");
  DOOR_DisplaySpecialScreen("ChatStart");
  if (N_ND->User->Valid)
  {
    N_ND->Actions[ACTN_CHATTEDTOSYSOP]=ACTC_CHATTEDTOSYSOP;
    DOOR_SysopText("Chatting To ");
    DOOR_SysopText(N_ND->User->CallData->Handle);
    DOOR_SysopText("\r\n\r\n");
  }

  DoChat();

  DOOR_DisplaySpecialScreen("ChatEnd");

}

int main(int argc,char *argv[])
{
  if (sscanf(argv[1],"%d",&N_NodeNum)==0)
  {
    printf("Invalid/No Paramaters for door!\n");
    exit (20);
  }
  init("SysopChat");

  if (BBSGlobal=HBBS_GimmeBBS())
  {
    if (N_ND=HBBS_NodeDataPtr(N_NodeNum)) // this should not fail in normal circumstances..
    {
      DoorMain(argc,argv);
    }
  }
  cleanup(0);
}
