/****************************************************************************
 * 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 "./watch.h"
#include "../client.h"
#include "../utils.h"

#include "aqhome/ipc2/endpoint.h"
#include "aqhome/msg/ipc/m_ipc.h"
#include "aqhome/msg/ipc/m_ipc_result.h"
#include "aqhome/msg/ipc/data/m_ipcd.h"
#include "aqhome/msg/ipc/data/m_ipcd_multidata.h"

#include <gwenhywfar/args.h>
#include <gwenhywfar/i18n.h>
#include <gwenhywfar/debug.h>
#include <gwenhywfar/text.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



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

static int _handleResponseMessage(AQH_OBJECT *o, const AQH_MESSAGE *msg, const GWEN_TAG16_LIST *tagList, int first);
static void _handleDataResponse(const AQH_MESSAGE *msg, const GWEN_TAG16_LIST *tagList, const char *tmpl);



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

int AQH_Tool_Watch(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, "brokerAddress",  0,  1,  "t",  "tcpaddress",  I18S("TCP address to connect to [127.0.0.1]"), NULL},
    { A_ARG, A_INT,  "brokerPort",     0,  1,  "P",  "tcpport",     I18S("Specify the TCP port to listen on"), NULL},
    { A_ARG, A_INT,  "timeout",        0,  1,  "T",  NULL,          I18S("Specify timeout in seconds for response"), NULL},
    { A_ARG, A_CHAR, "brokerClientId", 0,  1,  "c",  "clientid",    I18S("Specify CLIENTID"), NULL},
    { A_ARG, A_CHAR, "userId",         0,  1,  "u",  "userid",      I18S("Specify user id"), NULL},
    { A_ARG, A_CHAR, "password",       0,  1,  "p",  "password",    I18S("Specify service password"), NULL},
    { A_ARG, A_CHAR, "template",       0,  1,  NULL, "tmpl",        I18S("Specify template for output"), 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_DATA_ID, AQH_IPC_PROTOCOL_DATA_VERSION, dbGlobalArgs, args);
  AQH_ToolClient_AddFlags(o, AQH_TOOL_CLIENT_CONNECTFLAGS_WITHCONNECTMSG);
  AQH_ToolClient_AddFlags(o, AQH_ENDPOINT_FLAGS_WANTUPDATES);
  AQH_ToolClient_SetHandleResponseMessageFn(o, _handleResponseMessage);
  rv=AQH_ToolClient_ReadLocalArgs(o, argc, argv);
  if (rv!=0)
    return rv;
  rv=AQH_ToolClient_Watch(o);
  AQH_Object_free(o);
  AQH_EventLoop_free(eventLoop);
  return rv;
}



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

  dbArgs=AQH_ToolClient_GetDbLocalArgs(o);
  tmpl=GWEN_DB_GetCharValue(dbArgs, "template", 0, "$(datapoint/timestampAsDate)\t$(datapoint/datapoint)\t$(value/nameForSystem)");

  code=AQH_IpcMessage_GetCode(msg);
  if (code==AQH_MSGTYPE_IPC_DATA_DATACHANGED) {
    _handleDataResponse(msg, tagList, tmpl);
  }
  else {
    DBG_INFO(NULL, "Ignore message \"%d\"", code);
  }
  return 0;
}



void _handleDataResponse(GWEN_UNUSED const AQH_MESSAGE *msg, const GWEN_TAG16_LIST *tagList, const char *tmpl)
{
  AQH_VALUE *value;

  value=AQH_IpcdMessageMultiData_ReadValue(tagList);
  if (value) {
    uint64_t numberOfPoints;
    const uint64_t *dataPoints;

    AQH_IpcdMessageMultiData_ReadDatapoints(tagList, &dataPoints, &numberOfPoints);
    if (numberOfPoints>0 && dataPoints) {
      uint32_t i;

      for(i=0; i<numberOfPoints; i++) {
        uint64_t timestamp;
        union {double f; uint64_t i;} u;

        timestamp=*(dataPoints++);
        u.i=*(dataPoints++);
        Utils_PrintFormattedSingleDataPoint(value, timestamp, u.f, tmpl);
      }
    }
    AQH_Value_free(value);
  }
}



