#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "myc_err.h"
#include "myc_str.h"
#include "myc_time.h"
#include "myc_mem.h"
#include "tecs_cli.h"
#include "tecs_c.h"

static pTecsClient conn=NULL;
static char response[COC_RES_LEN];
static char *rwCode="rwacs";
static char *rdCode="rdacs";

char *TecsCmd(char *cmd) {
  char nbuf[64], *p, pbuf[4];
  int iret=-1, l;

  p=strchr(cmd, ' ');
  if (p==NULL) {
    str_copy(nbuf, cmd);
  } else {
    l=p-cmd;
    if (l>=sizeof(nbuf)) l=sizeof(nbuf)-1;
    strncpy(nbuf, cmd, l+1);
    nbuf[l]='\0';
    while (*p>'\0' && *p<=' ') p++;
    if (*p=='\0') p=NULL;
  }
  if (p==NULL) {
    CocReset(conn);
    ERR_I(CocGetStr(conn, nbuf, pbuf, sizeof(pbuf)));
    ERR_I(CocDoIt(conn, response, sizeof(response)));
  } else {
    CocReset(conn);
    ERR_I(CocPutStr(conn, nbuf, p));
    ERR_I(CocDoIt(conn, response, sizeof(response)));
  }
  return response;
  OnError: return ErrMessage;
}

char *TecsGet3(float *tset, float *texch, float *tsamp) {
  ERR_I(TeccGet3(conn, tset, texch, tsamp));
  return NULL;
  OnError: return ErrMessage;
}

char *TecsSet(float temp) {
  ERR_I(TeccSet(conn, temp));
  return NULL;
  OnError: return ErrMessage;
}

char *TecsInit(char *host, int port) {
  int iret;
  if (conn!=NULL) TeccClose(conn);
  NEW(conn, CocConn);
  if (host==NULL || *host=='\0') {
    ERR_I(iret=CocInitClient(conn, "", port, rwCode, 0, ""));
  } else {
    ERR_I(iret=CocInitClient(conn, host, port, rdCode, 0, ""));
  }
  if (iret==1) ErrShort("TECS_INIT: can not connect to TecsServer");
  return NULL;
  OnError:
    FREE(conn);
    return ErrMessage;
}

int TecsIsOpen(void) {
  return(conn!=NULL);
}

void TecsClose(void) {
  if (conn!=NULL) {
    TeccClose(conn);
    conn=NULL;
  }
}

