/****************************************************************************
 * This file is part of the project AqHome.
 * AqHome (c) by 2025 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 "./getnodes.h"
#include "../client.h"
#include "../utils.h"

#include "aqhome/msg/ipc/m_ipc.h"
#include "aqhome/msg/ipc/m_ipc_result.h"
#include "aqhome/msg/ipc/nodes/m_ipcn.h"
#include "aqhome/msg/ipc/nodes/m_ipcn_getdevices_req.h"
#include "aqhome/msg/ipc/nodes/m_ipcn_getdevices_rsp.h"
#include "aqhome/msg/node/m_node.h"
#include <aqhome/nodes/nodeinfo.h>

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

#include <ctype.h>



/* ------------------------------------------------------------------------------------------------
 * defs
 * ------------------------------------------------------------------------------------------------
 */

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

#define A_ARG GWEN_ARGS_FLAGS_HAS_ARGUMENT
#define A_END (GWEN_ARGS_FLAGS_HELP | GWEN_ARGS_FLAGS_LAST)
#define A_CHAR GWEN_ArgsType_Char
#define A_INT GWEN_ArgsType_Int

#define LAST1H (60*60)



/* ------------------------------------------------------------------------------------------------
 * forward declarations
 * ------------------------------------------------------------------------------------------------
 */

static AQH_MESSAGE *_createRequestMessage(AQH_OBJECT *o, uint32_t msgId);
static int _handleResponseMessage(AQH_OBJECT *o, const AQH_MESSAGE *msg, const GWEN_TAG16_LIST *tagList, int first);
static void _printNode(const AQH_NODE_INFO *ni, int printAll);
static void _printUintAsTextOrHex(uint32_t u, int bits);
static void _printDeviceIdAsTextOrHex(uint32_t u, int version);



/* ------------------------------------------------------------------------------------------------
 * code
 * ------------------------------------------------------------------------------------------------
 */

int AQH_Tool_GetNodes(GWEN_DB_NODE *dbGlobalArgs, int argc, char **argv)
{
  AQH_EVENT_LOOP *eventLoop;
  AQH_OBJECT *o;
  int rv;
  const GWEN_ARGS args[]= {
    /* flags type    name              min max s    long           short_descr, long_descr */
    { A_ARG, A_CHAR, "tcpAddress",     0,  1,  "t", "tcpaddress",  I18S("TCP address to connect to [127.0.0.1]"), NULL},
    { A_ARG, A_INT,  "tcpPort",        0,  1,  "P", "tcpport",     I18S("TCP port to connect to"), NULL},
    { A_ARG, A_INT,  "timeout",        0,  1,  "T", NULL,          I18S("Specify timeout in seconds for response"), NULL},
    { 0,     A_INT,  "printHeader",    0,  1,  "H", "printheader", I18S("Print header if given"), NULL},
    { 0,     A_INT,  "printAll",       0,  1,  "a", "printall",    I18S("Print all devices (not only last seen)"), NULL},
    { A_END, A_INT,  "help",           0,  0,  "h", "help",        I18S("Show this help screen"), NULL}
  };

  eventLoop=AQH_EventLoop_new();
  o=AQH_ToolClient_new(eventLoop, AQH_IPC_PROTOCOL_NODES_ID, AQH_IPC_PROTOCOL_NODES_VERSION, dbGlobalArgs, args);
  AQH_ToolClient_SetFlags(o, AQH_TOOL_CLIENT_CONNECTFLAGS_WITHCONNECTMSG);

  AQH_ToolClient_SetCreateRequestMessageFn(o, _createRequestMessage);
  AQH_ToolClient_SetHandleResponseMessageFn(o, _handleResponseMessage);
  rv=AQH_ToolClient_ReadLocalArgs(o, argc, argv);
  if (rv!=0)
    return rv;
  rv=AQH_ToolClient_Run(o);
  AQH_Object_free(o);
  AQH_EventLoop_free(eventLoop);
  return rv;
}



AQH_MESSAGE *_createRequestMessage(GWEN_UNUSED AQH_OBJECT *o, uint32_t msgId)
{
  return AQH_IpcnMessageGetDevicesReq_new(AQH_MSGTYPE_IPC_NODES_GETDEVICES_REQ, msgId, 0);
}



int _handleResponseMessage(GWEN_UNUSED AQH_OBJECT *o, const AQH_MESSAGE *msg, const GWEN_TAG16_LIST *tagList, int first)
{
  uint16_t code;
  GWEN_DB_NODE *dbArgs;
  //int printHeader;
  int printAll;

  dbArgs=AQH_ToolClient_GetDbLocalArgs(o);
  //printHeader=first?GWEN_DB_GetIntValue(dbArgs, "printHeader", 0, 0):0;
  printAll=GWEN_DB_GetIntValue(dbArgs, "printAll", 0, 0);

  code=AQH_IpcMessage_GetCode(msg);
  if (code==AQH_MSGTYPE_IPC_NODES_GETDEVICES_RSP) {
    AQH_NODE_INFO *ni;

    ni=AQH_IpcnMessageGetDevicesRsp_ReadNodeInfo(tagList);
    if (ni)
      _printNode(ni, printAll);

    if (AQH_IpcnMessageGetDevicesRsp_GetFlags(tagList) & AQH_MSGNODE_GETDEVICES_RSP_FLAGS_LASTMSG) {
      DBG_INFO(NULL, "Last message received");
      return 1;
    }
    return 0;
  }
  else if (code==AQH_MSGTYPE_IPC_NODES_RESULT)
    return AQH_ToolClient_HandleResultMsg(msg, tagList, first);
  else {
    DBG_INFO(NULL, "Unexpected message \"%d\"", code);
    return 3;
  }
}




void _printNode(const AQH_NODE_INFO *ni, int printAll)
{
  const GWEN_TIMESTAMP *ts;
  time_t now;
  time_t tLastSeen=0;
  int timeSinceLastSeen;

  now=time(NULL);
  ts=AQH_NodeInfo_GetTimestampLastChange(ni);
  tLastSeen=ts?GWEN_Timestamp_toTimeT(ts):now;
  timeSinceLastSeen=(int) (now-tLastSeen);
  if (printAll || timeSinceLastSeen<LAST1H) {
    uint32_t u;

    fprintf(stdout, "- node: addr=%3d, uid=0x%08x, device=",
	    AQH_NodeInfo_GetBusAddress(ni),
	    (unsigned int) AQH_NodeInfo_GetUid(ni));

    u=AQH_NodeInfo_GetManufacturer(ni);
    _printUintAsTextOrHex(u, 32);
    fprintf(stdout, ":");
    u=AQH_NodeInfo_GetDeviceType(ni);
    _printDeviceIdAsTextOrHex(u, AQH_NodeInfo_GetDeviceVersion(ni));
    u=AQH_NodeInfo_GetFirmwareVersion(ni);
    fprintf(stdout, ", firmware=%d.%d.%d (%d), ",
	    (u>>16) & 0xff, (u>>8) & 0xff, u & 0xff, (u>>24) & 0xff);
    if (ts)
      fprintf(stdout, "last seen %04d/%02d/%02d-%02d:%02d:%02d, ",
              GWEN_Timestamp_GetYear(ts),
              GWEN_Timestamp_GetMonth(ts),
              GWEN_Timestamp_GetDay(ts),
              GWEN_Timestamp_GetHour(ts),
              GWEN_Timestamp_GetMinute(ts),
              GWEN_Timestamp_GetSecond(ts));
    fprintf(stdout, "pkg out: %d, pkg in: %d, busy: %d, crc: %d, io: %d, heap used: %d, heap free: %d, xram: %d\n",
	    AQH_NodeInfo_GetStatsPacketsOut(ni),
	    AQH_NodeInfo_GetStatsPacketsIn(ni),
	    AQH_NodeInfo_GetStatsBusy(ni),
	    AQH_NodeInfo_GetStatsCrcErrors(ni),
            AQH_NodeInfo_GetStatsIoErrors(ni),
            AQH_NodeInfo_GetStatsHeapUsed(ni),
            AQH_NodeInfo_GetStatsHeapFree(ni),
            AQH_NodeInfo_GetStatsXramSize(ni));
  }
}



void _printDeviceIdAsTextOrHex(uint32_t u, int version)
{
  int i;
  uint8_t d;
  int hasNonPrintable=0;
  int hasPrintable=0;

  for (i=0; i<16; i+=8) {
    d=((u>>i) & 0xff);
    if (d==0) { /* undecided */
    }
    else if (isalnum(d))
      hasPrintable=1;
    else
      hasNonPrintable=1;
  }
  if (hasNonPrintable || !hasPrintable)
      fprintf(stdout, "%02x v%d.%d", u, (version>>8) & 0xff, version & 0xff);
  else {
    for (i=0; i<16; i+=8) {
      d=((u>>i) & 0xff);

      fprintf(stdout, "%c", d?d:' ');
    }
    fprintf(stdout, "%2d (%d)", (version>>8) & 0xff, version & 0xff);
  }
}



void _printUintAsTextOrHex(uint32_t u, int bits)
{
  int i;
  uint8_t d;
  int hasNonPrintable=0;
  int hasPrintable=0;

  for (i=0; i<bits; i+=8) {
    d=((u>>i) & 0xff);
    if (d==0) { /* undecided */
    }
    else if (isalnum(d))
      hasPrintable=1;
    else
      hasNonPrintable=1;
  }
  if (hasNonPrintable || !hasPrintable)
    fprintf(stdout, "%08x", u);
  else {
    for (i=0; i<bits; i+=8) {
      d=((u>>i) & 0xff);

      fprintf(stdout, "%c", d?d:' ');
    }
  }
}


