
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include "aqhome/hexfile/hexfile.h"
#include "aqhome/hexfile/flashrecord.h"

#include "aqhome/events2/eventloop.h"
#include "aqhome/events2/fdobject.h"
#include "aqhome/ipc2/tty_object.h"
#include "aqhome/ipc2/node_msgreader.h"
#include "aqhome/ipc2/msgreader.h"
#include "aqhome/ipc2/msgwriter.h"
#include "aqhome/ipc2/endpoint.h"
#include "aqhome/ipc2/tty_endpoint.h"

#include "aqhome/aqhome.h"

#include <gwenhywfar/debug.h>
#include <gwenhywfar/text.h>
#include <gwenhywfar/gwentime.h>
#include <gwenhywfar/buffer.h>
#include <gwenhywfar/endpoint_tcpd.h>
#include <gwenhywfar/endpoint_msgio.h>
#include <gwenhywfar/endpoint_multilayer.h>

#include <unistd.h>
#include <time.h>



#if 0
GWEN_MSG_ENDPOINT *_acceptHttpConnection(GWEN_UNUSED GWEN_MSG_ENDPOINT *ep,
                                         GWEN_SOCKET *sk,
                                         GWEN_UNUSED const GWEN_INETADDRESS *addr,
                                         GWEN_UNUSED void *data)
{
  GWEN_MSG_ENDPOINT *epIncoming;

  DBG_INFO(GWEN_LOGDOMAIN, "Incoming connection");
  //epIncoming=GWEN_IpcEndpoint_CreateIpcTcpServiceForSocket(sk, NULL, 1);
  epIncoming=GWEN_MsgEndpoint_new("HTTP-Service", 0);
  GWEN_MsgEndpoint_SetSocket(epIncoming, sk);
  GWEN_MsgIoEndpoint_Extend(epIncoming);
  AQH_HttpEndpoint_Extend(epIncoming, AQH_ENDPOINT_HTTP_FLAGS_PASSIVE);
  return epIncoming;
}



int testHttpDaemon()
{
  GWEN_MSG_ENDPOINT *epServer;
  int loop;

  AQH_Init();
  epServer=GWEN_TcpdEndpoint_new("127.0.0.1", 55556, NULL, 1);
  GWEN_TcpdEndpoint_SetAcceptFn(epServer, _acceptHttpConnection, NULL);

  for (loop=0;; loop++) {
    GWEN_MSG_ENDPOINT *ep;

    DBG_INFO(GWEN_LOGDOMAIN, "Loop %d:", loop);
    GWEN_MsgEndpoint_IoLoop(epServer, 2000); /* 2000 ms */
    ep=GWEN_MsgEndpoint_Tree2_GetFirstChild(epServer);
    while(ep) {
      GWEN_MSG *msg;

      DBG_INFO(GWEN_LOGDOMAIN, "- Checking endpoint");
      while( (msg=GWEN_MsgEndpoint_TakeFirstReceivedMessage(ep)) ) {
        GWEN_DB_NODE *db;
        GWEN_BUFFER *buf;
        GWEN_MSG *msgOut;

        DBG_INFO(GWEN_LOGDOMAIN, "  - received msg");
        db=GWEN_Msg_GetDbParsedInfo(msg);
        if (db)
          GWEN_DB_Dump(db, 2);

        buf=GWEN_Buffer_new(0, 256, 0, 1);
        GWEN_Buffer_AppendString(buf, "HTTP/1.1 200 Okay\r\n");
        GWEN_Buffer_AppendString(buf, "Connection: close\r\n");
        GWEN_Buffer_AppendString(buf, "Content-length: 23\r\n");
        GWEN_Buffer_AppendString(buf, "\r\n");
        GWEN_Buffer_AppendString(buf, "This is a test string\r\n");
        msgOut=GWEN_Msg_fromBytes((const uint8_t*)GWEN_Buffer_GetStart(buf), GWEN_Buffer_GetUsedBytes(buf));
        GWEN_Buffer_free(buf);
        GWEN_MsgEndpoint_AddSendMessage(ep, msgOut);
        GWEN_Msg_free(msg);
      } /* while */
      ep=GWEN_MsgEndpoint_Tree2_GetNext(ep);
    }
    GWEN_MsgEndpoint_RemoveUnconnectedAndEmptyChildren(epServer);
  }
  return 0;
}
#endif


int testHexfile(int argc, char **argv)
{
  const char *inFilename;
  const char *outFilename;
  AQH_HEXFILE *h;
  int rv;

  if (argc<3) {
    fprintf(stderr, "Missing filenames (in, out)\n");
    return 1;
  }

  rv=AQH_Init();
  if (rv<0) {
  }

  inFilename=argv[1];
  outFilename=argv[2];
  h=AQH_Hexfile_fromFile(inFilename);
  if (h==NULL) {
    fprintf(stderr, "Error reading hexfile \"%s\".\n", inFilename);
    return 2;
  }
  else {
    AQH_HEXFILERECORD_LIST *recordList;
    GWEN_BUFFER *buffer;

    recordList=AQH_Hexfile_GetRecordList(h);
    fprintf(stdout, "INTEL Hexfile read with %d records\n", AQH_HexfileRecord_List_GetCount(recordList));

    buffer=GWEN_Buffer_new(0, 1024, 0, 1);
    AQH_Hexfile_toBuffer(h, buffer);
    rv=GWEN_SyncIo_Helper_WriteFile(outFilename, (const uint8_t*) GWEN_Buffer_GetStart(buffer), GWEN_Buffer_GetUsedBytes(buffer));
    GWEN_Buffer_free(buffer);
    if (rv<0) {
      fprintf(stderr, "ERROR writing outfile \"%s\": %d", outFilename, rv);
      AQH_Hexfile_free(h);
      return 3;
    }
    AQH_Hexfile_free(h);
  }

  return 0;
}



int testFlashRecords(int argc, char **argv)
{
  const char *inFilename;
  AQH_HEXFILE *h;
  int rv;

  if (argc<2) {
    fprintf(stderr, "Missing filename\n");
    return 1;
  }

  rv=AQH_Init();
  if (rv<0) {
  }

  inFilename=argv[1];
  h=AQH_Hexfile_fromFile(inFilename);
  if (h==NULL) {
    fprintf(stderr, "Error reading hexfile \"%s\".\n", inFilename);
    return 2;
  }
  else {
    AQH_HEXFILERECORD_LIST *recordList;
    AQH_FLASHRECORD_LIST *flashRecordList;

    recordList=AQH_Hexfile_GetRecordList(h);
    fprintf(stdout, "INTEL Hexfile read with %d records\n", AQH_HexfileRecord_List_GetCount(recordList));

    flashRecordList=AQH_FlashRecord_fromHexfileRecords(recordList);
    if (flashRecordList==NULL) {
      fprintf(stderr, "ERROR creating flash record list\n");
      AQH_Hexfile_free(h);
      return 3;
    }
    else {
      AQH_FLASHRECORD *fr;

      fprintf(stdout, "Flash record list created with %d records\n", AQH_FlashRecord_List_GetCount(flashRecordList));
      fr=AQH_FlashRecord_List_First(flashRecordList);
      while(fr) {
        fprintf(stdout, "- %08x (%d bytes)\n", AQH_FlashRecord_GetAddress(fr), AQH_FlashRecord_GetDataLength(fr));
        fr=AQH_FlashRecord_List_Next(fr);
      }
    }

    AQH_Hexfile_free(h);
  }

  return 0;
}



int testTty(int argc, char **argv)
{
  const char *deviceName;
  AQH_EVENT_LOOP *eventLoop;
  struct termios initialTermiosState;
  int fd;
  AQH_OBJECT *ttyReadObject;
  AQH_OBJECT *msgReaderObject;
  AQH_OBJECT *endpointObject;
  int rv;

  if (argc<2) {
    fprintf(stderr, "Missing device name\n");
    return 1;
  }

  rv=AQH_Init();
  if (rv<0) {
  }

  deviceName=argv[1];

  eventLoop=AQH_EventLoop_new();
  fd=AQH_TtyObject_OpenAndInitDevice(deviceName, &initialTermiosState);
  if (fd<0) {
    fprintf(stderr, "Error opening device \"%s\"\n", deviceName);
    return 2;
  }

  ttyReadObject=AQH_TtyObject_new(eventLoop, fd, AQH_FDOBJECT_FDMODE_READ);
  AQH_FdObject_FlushInput(ttyReadObject);
  msgReaderObject=AQH_NodeMsgReader_new(eventLoop, ttyReadObject);
  endpointObject=AQH_Endpoint_new(eventLoop, msgReaderObject, NULL);

  AQH_Object_Enable(msgReaderObject);

  for (;;) {
    AQH_EventLoop_Run(eventLoop, 500);
  }

  return 0;
}



int testTty2(int argc, char **argv)
{
  const char *deviceName;
  AQH_EVENT_LOOP *eventLoop;
  struct termios initialTermiosState;
  int fd;
  AQH_OBJECT *endpointObject;
  int rv;

  if (argc<2) {
    fprintf(stderr, "Missing device name\n");
    return 1;
  }

  rv=AQH_Init();
  if (rv<0) {
  }

  deviceName=argv[1];

  eventLoop=AQH_EventLoop_new();
  fd=AQH_TtyObject_OpenAndInitDevice(deviceName, &initialTermiosState);
  if (fd<0) {
    fprintf(stderr, "Error opening device \"%s\"\n", deviceName);
    return 2;
  }

  endpointObject=AQH_TtyEndpoint2_new(eventLoop, fd, 0);

  for (;;) {
    AQH_EventLoop_Run(eventLoop, 500);
  }

  return 0;
}




int main(int argc, char **argv)
{
  //return testHexfile(argc, argv);
  //return testFlashRecords(argc, argv);
  //return testMqttConnection2();
  //return testMqttSubscribe2(argc, argv);
  //return testHttpDaemon();
  //return testMqttSubscribe3(argc, argv);
  return testTty2(argc, argv);
  return 0;
}


