#include "ascon.h"
#include "ascon.i"

/*
 * this is a scriptcontext driver connecting to its own sics server.
 * after a send command the configured polling script is called repeatedly
 * with the sent command as argument until it returns something else than 0
 *
 * Markus Zolliker Aug 2011
 */

/*----------------------------------------------------------------------------*/
int DumProtHandler(Ascon *a)
{
  Tcl_Interp *pTcl;
  int ret;

  char *result = NULL;
  int iRet = 1;

  switch (a->state) {
  case AsconConnectStart:
  case AsconConnecting:
    a->state = AsconConnectDone;
    break;
  case AsconWriteStart:
    DynStringInsert(a->wrBuffer, " ", 0);
    DynStringInsert(a->wrBuffer, a->hostport, 0);
  case AsconWriting:
    a->state = AsconWriteDone;
    break;
  case AsconReadStart:
  case AsconReading:
    pTcl = InterpGetTcl(pServ->pSics);
    ret = Tcl_EvalEx(pTcl, GetCharArray(a->wrBuffer), GetDynStringLength(a->wrBuffer), 0);
    result = (char *) Tcl_GetStringResult(pTcl);
    DynStringCopy(a->rdBuffer, result);
    if (ret != TCL_OK || strcmp(result, "0") != 0) {
      a->state = AsconReadDone;
    }
    break;
  }
  return 0;
}

/*----------------------------------------------------------------------------*/
static int DumProtInit(Ascon * a, SConnection * con, int argc, char *argv[])
{
  /* argv[1] is the polling script. stored in hostport */
  a->hostport = strdup(argv[1]);
  return 1;
}

/*----------------------------------------------------------------------------*/
void AddDumProtocol()
{
  static AsconProtocol dumprot;
  dumprot.name = "dumprot";
  dumprot.handler = DumProtHandler;
  dumprot.init = DumProtInit;
  AsconInsertProtocol(&dumprot);
}
