#include "puma.h"
#include "libpuma.h"
#include <stdio.h>
#include <string.h>
#include "network/PrSocket.h"
#include "driver/PrUtility.h"

#define PR_TYPE_ACTION         0
#define PR_TYPE_FLOAT          1

#define PR_ACTION_NONE         0
#define PR_ACTION_OPEN         1
#define PR_ACTION_CLOSE        2
#define PR_ACTION_EXIT         3
#define PR_ACTION_STOP         4
#define PR_ACTION_FLOAT        5
#define PR_ACTION_GOTO         6
#define PR_ACTION_RESET        7
#define PR_ACTION_SET_GOAL     8
#define PR_ACTION_SYNC         9

int GetLine(FILE *stream,char *line,int max)
{
  int i,c=EOF;

  for (i = 0; i < max-1 && (c = fgetc(stream)) != EOF && c != '\n'; i++) {
    if (c == '\b' && i>0) {
        i -= 2;
    } else {
        line[i] = (char)c;
    }
  }
  line[i] = '\0';
  if (c == EOF && i == 0) return -1;
  else return i;
}

void main()
{
  PrUtility *util = new PrUtility;

  PrSocket *clientServo = new PrSocket("localhost",
				       PUMA_USER_SERVO_TCP_PORT);
  if (clientServo->flag() != PR_SOCKET_OK)
    perror("client: can't create error");
  
  PrDataInput *inServo = new PrDataInput(clientServo);
  PrDataOutput *outServo = new PrDataOutput(clientServo);

  PrSocket *clientGather = new PrSocket("localhost",
					PUMA_USER_GATHER_TCP_PORT);
  if (clientGather->flag() != PR_SOCKET_OK)
    perror("client: can't create error");
  
  PrDataInput *inGather = new PrDataInput(clientGather);
  PrDataOutput *outGather = new PrDataOutput(clientGather);

  int action,n;
  char buffer[PUMA_BUFFER_SIZE];
  int done=0;

  printf("start: User\n");
  fflush(stdout);
  int count = 1;
  int bufferlen;

  while(done != 1)
    {
      memset(buffer,PUMA_BUFFER_SIZE,NULL);

      printf("\npuma: %d> ",count);
      fflush(stdout);
      bufferlen=GetLine(stdin,buffer,PUMA_BUFFER_SIZE);
      if (bufferlen > 0) 
	{
	  if (strncmp(buffer,"exit",4)==0)
	    {
	      action = PUMA_ACTION_EXIT;
	      n = outGather->writeInt(&action,1);
	      if (outGather->flush(PUMA_TYPE_ACTION) != n)
		{
		  printf("write error\n");
		}
	      done = 1;
	    }
	  n = outServo->writeChar(buffer,bufferlen);
	  if (outServo->flush(PUMA_TYPE_CHAR)!=n)
	    {
	      printf("write error\n");
	    } 
	  count++;
	}
      util->microBlock(2000);
    }
  delete inServo;
  delete outServo;
  clientServo->close();
  delete clientServo;
  delete inGather;
  delete outGather;
  clientGather->close();
  delete clientGather;
  delete util;
}

