/****************************************************************************
 * This file is part of the project AqHome.
 * AqHome (c) by 2023 Martin Preuss, all rights reserved.
 *
 * The license for this file can be found in the file COPYING which you
 * should have received along with this file.
 ****************************************************************************/

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

#include "./ping.h"
#include "../utils.h"

#include "aqhome/ipc/nodes/msg_ipc_setaccmsggrps.h"
#include "aqhome/ipc/nodes/msg_ipc_ping.h"
#include "aqhome/ipc/nodes/msg_ipc_forward.h"
#include "aqhome/ipc/endpoint_ipc.h"
#include "aqhome/msg/msg_node.h"

#include <gwenhywfar/args.h>
#include <gwenhywfar/i18n.h>
#include <gwenhywfar/debug.h>
#include <gwenhywfar/text.h>

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


#define I18S(msg) msg
#define I18N(msg) GWEN_I18N_Translate(PACKAGE, msg)



static int _doPing(GWEN_DB_NODE *dbArgs);
static int _sendPing(GWEN_MSG_ENDPOINT *epTcp, int nodeAddr);



int AQH_Tool_Ping(GWEN_DB_NODE *dbGlobalArgs, int argc, char **argv)
{
  GWEN_DB_NODE *dbLocalArgs;
  int rv;
  const GWEN_ARGS args[]= {
    {
      GWEN_ARGS_FLAGS_HAS_ARGUMENT, /* flags */
      GWEN_ArgsType_Char,           /* type */
      "tcpAddress",                 /* name */
      0,                            /* minnum */
      1,                            /* maxnum */
      "t",                          /* short option */
      "tcpaddress",                 /* long option */
      I18S("Specify TCP address to connect to (defaults to 127.0.0.1)"),
      I18S("Specify TCP address to connect to (defaults to 127.0.0.1)")
    },
    {
      GWEN_ARGS_FLAGS_HAS_ARGUMENT, /* flags */
      GWEN_ArgsType_Int,            /* type */
      "tcpPort",                    /* name */
      0,                            /* minnum */
      1,                            /* maxnum */
      "P",                          /* short option */
      "tcpport",                    /* long option */
      I18S("Specify the TCP port to listen on"),
      I18S("Specify the TCP port to listen on")
    },
    {
      GWEN_ARGS_FLAGS_HAS_ARGUMENT, /* flags */
      GWEN_ArgsType_Int,            /* type */
      "nodeAddr",                   /* name */
      1,                            /* minnum */
      1,                            /* maxnum */
      "n",                          /* short option */
      "nodeaddr",                    /* long option */
      I18S("Specify bus addr of the node to ping"),
      I18S("Specify bus addr of the node to ping")
    },
    {
      GWEN_ARGS_FLAGS_HAS_ARGUMENT, /* flags */
      GWEN_ArgsType_Int,            /* type */
      "timeout",                    /* name */
      0,                            /* minnum */
      1,                            /* maxnum */
      "T",                          /* short option */
      NULL,                         /* long option */
      I18S("Specify timeout in seconds for PONG response"),
      I18S("Specify timeout in seconds for PONG response")
    },
    {
      GWEN_ARGS_FLAGS_HELP | GWEN_ARGS_FLAGS_LAST, /* flags */
      GWEN_ArgsType_Int,             /* type */
      "help",                       /* name */
      0,                            /* minnum */
      0,                            /* maxnum */
      "h",                          /* short option */
      "help",                       /* long option */
      "Show this help screen",      /* short description */
      "Show this help screen"       /* long description */
    }
  };

  dbLocalArgs=GWEN_DB_GetGroup(dbGlobalArgs, GWEN_DB_FLAGS_DEFAULT, "local");
  rv=GWEN_Args_Check(argc, argv, 1,
                     GWEN_ARGS_MODE_ALLOW_FREEPARAM,
                     args,
                     dbLocalArgs);
  if (rv==GWEN_ARGS_RESULT_ERROR) {
    fprintf(stderr, "ERROR: Could not parse arguments\n");
    return 1;
  }
  else if (rv==GWEN_ARGS_RESULT_HELP) {
    GWEN_BUFFER *ubuf;

    ubuf=GWEN_Buffer_new(0, 1024, 0, 1);
    if (GWEN_Args_Usage(args, ubuf, GWEN_ArgsOutType_Txt)) {
      fprintf(stderr, "ERROR: Could not create help string\n");
      return 1;
    }
    fprintf(stderr, "%s\n", GWEN_Buffer_GetStart(ubuf));
    GWEN_Buffer_free(ubuf);
    return 0;
  }

  return _doPing(dbLocalArgs);
}



int _doPing(GWEN_DB_NODE *dbArgs)
{
  GWEN_MSG_ENDPOINT *epTcp;
  int rv;
  int nodeAddr;
  int timeoutInSeconds;
  GWEN_MSG *msg;

  epTcp=Utils_SetupNodesClientEndpoint(dbArgs);
  if (epTcp==NULL) {
    DBG_ERROR(NULL, "ERROR creating TCP connection");
    return 2;
  }

  nodeAddr=GWEN_DB_GetIntValue(dbArgs, "nodeAddr", 0, 0);
  timeoutInSeconds=GWEN_DB_GetIntValue(dbArgs, "timeout", 0, 5);

  rv=Utils_SendAcceptedMsgGroups(epTcp, AQH_MSG_TYPEGROUP_ALL);
  if (rv<0) {
    DBG_INFO(NULL, "here (%d)", rv);
    return 2;
  }

  fprintf(stdout, "Sending PING request\n");

  rv=_sendPing(epTcp, nodeAddr);
  if (rv<0) {
    DBG_INFO(NULL, "here (%d)", rv);
    return 2;
  }

  msg=Utils_WaitForSpecificNodeMessage(epTcp, AQH_MSG_TYPE_PONG, nodeAddr, timeoutInSeconds);
  if (msg==NULL) {
    DBG_INFO(NULL, "No PONG response received.");
    return 2;
  }

  fprintf(stdout, "PONG response received\n");
  GWEN_MsgEndpoint_free(epTcp);
  return 0;
}



int _sendPing(GWEN_MSG_ENDPOINT *epTcp, int nodeAddr)
{
  GWEN_MSG *msgOut;

  msgOut=AQH_PingIpcMsg_new(AQH_MSGTYPE_IPC_NODES_PING, nodeAddr);
  if (msgOut==NULL) {
    DBG_ERROR(NULL, "Error creating message");
    return GWEN_ERROR_GENERIC;
  }
  GWEN_MsgEndpoint_AddSendMessage(epTcp, msgOut);
  return 0;
}






