#include <ctype.h>
#include <math.h>
#include <errno.h>
#include "ascon.h"
#include "ascon.i"
#include "dynstring.h"
#include "cnvrt.h"

/*
 * this is a driver for connection to an other sea (or sics) server
 *
 * Markus Zolliker June 2012
 *
 */

/*----------------------------------------------------------------------------*/
int SeaClientHandler(Ascon *a) {
  int ret;
  char chr;
  int tmo;
  char *line;
  int result;
  
  switch (a->state) {
  case AsconWriteStart:
    line = GetCharArray(a->wrBuffer);
    if (strncasecmp(line, "fulltransact", 12) == 0) {
      a->readState = 0;
    } else if (strncasecmp(line, "transact", 8) == 0) {
      a->readState = 1;
    } else if (strstr(line, "\ntransAct ") != 0) {
      a->readState = 1;
    } else {
      a->readState = 2;
    }
    a->lineCount = 0; /* used as position to beginning of line */
    break;
  case AsconReading:
    result = AsconBaseHandler(a);
    if (result == 0)
      return 0;
    chr = a->lastChar;
    if (chr == '\n') {
      line = GetCharArray(a->rdBuffer) + a->lineCount;
      switch (a->readState) {
      case 0:
        if (strncmp(line, "TRANSACTIONSTART", 16) == 0) {
          a->readState = 1;
          DynStringClear(a->rdBuffer);
        }
        break;
      case 1:
        if (strncmp(line, "TRANSACTIONFINISHED", 19) == 0) {
          a->state = AsconReadDone;
          if (a->lineCount > 0) {
            a->lineCount--;
          }
          DynStringShorten(a->rdBuffer, a->lineCount);
        }
        break;
      case 2:
        a->state = AsconReadDone;
        DynStringBackspace(a->rdBuffer);
        break;
      }
      a->lineCount = GetDynStringLength(a->rdBuffer); /* set position of new line */
    }
    return 1;
  }
  return AsconBaseHandler(a);
}
/*----------------------------------------------------------------------------*/
static int SeaClientInit(Ascon * a, SConnection * con, int argc, char *argv[])
{  
  a->hostport = strdup(argv[1]);
  if (argc > 2) {
    a->timeout = atof(argv[2]);
  } else {
    a->timeout = 5.0;
  }
  a->sendTerminator = strdup("\n");
  return 1;
}

/*----------------------------------------------------------------------------*/
void AddSeaClientProtocol()
{
  static AsconProtocol seaclientprot;
  seaclientprot.name = "seaclient";
  seaclientprot.handler = SeaClientHandler;
  seaclientprot.init = SeaClientInit;
  AsconInsertProtocol(&seaclientprot);
}
