#include <signal.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "Syslog.h"
#include "System.h"
#include "AdaptiveSamplerIF.h"
#include "GulperIF.h"
#include "GulperDefs.h"
#include "AdaptiveSampler.h"
#include "SerialParameters.h"


void signalHandler(int signalNo);

pid_t adaptiveSamplerPID;
pid_t gulperPID;
//pid_t clusterPID;

void signalHandler(int signalNo)
{
  kill(adaptiveSamplerPID, SIGTERM);
  kill(gulperPID, SIGTERM);
//kill(clusterPID, SIGTERM);
  kill(0, SIGQUIT);
  exit(0);
}

int main(int argc, char **argv)
{
  //
  SerialParameters serialParams(&argc, argv);
  char argString[100];
  DeviceIF::Status status;
  AdaptiveSamplerIF::GULPERS_TO_ARM_T gulpersToArm;

  for( int i=0; i< NGULPERS; i++ ) gulpersToArm[i] = False;

  signal(SIGQUIT, signalHandler);

  sprintf(argString, "-serial %s", serialParams.string());

  printf("Starting gulperServer ...\n");
  if ( (gulperPID = System::spawn("gulperServer", argString)) == -1) 
  {
    fprintf(stderr, "System::spawn(gulperServer) failed\n");
    exit(-1);
  }

  printf("Starting adaptiveSamplerServer ...\n");
  if ( (adaptiveSamplerPID = System::spawn("adaptiveSamplerServer", "True"))
       == -1) 
  {
    fprintf(stderr, "System::spawn(adaptiveSamplerServer) failed\n");
    exit(-1);
  }
#if 0
  printf("Starting clusterServer ...\n");
  if ( (clusterPID = System::spawn("clusterServer", ""))
       == -1) 
  {
    fprintf(stderr, "System::spawn(clusterServer) failed\n");
    exit(-1);
  }
#endif
  //
  // Now get a handle to the server IF
  //
  AdaptiveSamplerIF *adaptiveSampler;
  try {
    adaptiveSampler = new AdaptiveSamplerIF("AdaptiveSampler");
  }
  catch (Exception e) 
  {
    Syslog::write(
        "adaptiveSamplerTest -- Caught exception on creation of AdaptiveSamplerIF:%s\n",
		  e.msg);
    exit( -1 );
  }
  //
  // Now get a handle to the Gulper IF
  //
  GulperIF *gulper;
  try {
    gulper = new GulperIF("Gulper");
  }
  catch (Exception e) 
  {
    Syslog::write(
        "adaptiveSamplerTest -- Caught exception on creation of GulperIF:%s\n",
		  e.msg);
    exit( -1 );
  }

  TimeIF::TimeSpec updateTime;
  //AdaptiveSamplerIF::GulperState gulperState[NGULPERS];
  short gulperState[NGULPERS];
  char str[32];

  char buf[256];
  char *helpStr = "Valid commands are:\n"
                  "   help   - Help\n"
                  "   arm n  - Arm gulper number n.\n"
                  "   cnt    - Number of driver iterations.\n"
                  "   state  - State of each gulper.\n"
                  "   fire n - Fire a gulper.\n"
                  "   quit   - Quit.\n";
  while (True) 
  {
     printf("AdaptiveSamplerTest> ");
     if (gets(buf) == 0) continue;  // Some error occurred

     if ( !strncmp(buf, "help", 1) || !strncmp(buf, "Help", 1) || 
	  !strncmp(buf, "" , 1) )
     {
	printf("%s",helpStr);
     }
     else if (!strncmp(buf, "cnt", 3 )) 
     {
	printf("Number of samples: %d\n", 
	       adaptiveSampler->counter() );
     }
     else if (!strncmp(buf, "fire", 2 )) 
     {
	int   index;
	char *token = strtok(buf, " \t");
	while( token = strtok(0, " \t") )
	{
	   index = atoi(token);
	   if( index < 0 || index >= NGULPERS )
	   {
	      printf("Illegal gulper number %d\n", index);
	      break;
	   }
	   gulper->fireGulper(index);
	   printf("Fire request for gulper %d\n", index);
	}	   
     }
     else if (!strncmp(buf, "state", 2 )) 
     {
	adaptiveSampler->state( gulperState );
	for( int i=0; i<NGULPERS; i++ )
	{
	   if( gulperState[i] == AdaptiveSamplerIF::Unarmed )
	      strcpy( str, "Unarmed" );
	   else if( gulperState[i] == AdaptiveSamplerIF::Armed )
	      strcpy( str, "Armed" );
	   else if( gulperState[i] == AdaptiveSamplerIF::Fired )
	      strcpy( str, "Fired" );
	   else printf("Gulper%d is in an unknown state.\n", i);
	   printf("Gulper%d is %s.\n", i, str);
	}
     }
     else if (!strncmp(buf, "arm", 3 )) 
     {
	//
	// First zero out the array
	for( int j=0; j<NGULPERS; j++ ) gulpersToArm[j] = False;

	int   index;
	char *token = strtok(buf, " \t");
	while( token = strtok(0, " \t") )
	{
	   index = atoi(token);
	   if( index < 0 || index >= NGULPERS )
	   {
	      printf("Illegal gulper number %d\n", index);
	      break;
	   }
	   gulpersToArm[index] = True;
	   printf("Arm gulper %d\n", index);
	}	   
	adaptiveSampler->armGulper(gulpersToArm);
     }
     else if ( !strncmp(buf, "q", 1 ) || !strncmp(buf, "Q", 1 ) ) break;
     else printf(" Error: Command unrecognized.\n %s", helpStr);
  }

  // Just wait for termination signal
  signalHandler(0);
  return 0;
}

