/****************************************************************************
 * 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 "./adddata.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/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>
#include <gwenhywfar/json_read.h>
#include <gwenhywfar/json_dump.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 AQH_MESSAGE *_createRequestMessage(AQH_OBJECT *o, uint32_t msgId);
static GWEN_JSON_ELEM *_readJsonFile(const char *filename);



/* ------------------------------------------------------------------------------------------------
 * implementations
 * ------------------------------------------------------------------------------------------------
 */

int AQH_Tool_AddDataPoint(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, "valueName",      1,  1,  "N",  "valuename",   I18S("Value name (e.g. server/temp/system)"), NULL},
    { A_ARG, A_CHAR, "valueUnits",     0,  1,  "U",  "valueunits",  I18S("Value units (e.g. \"Grad Celsius\")"), NULL},
    { A_ARG, A_CHAR, "value",          1,  1,  "v",  "value",       I18S("Value to set"), NULL},
    { A_ARG, A_CHAR, "device",         1,  1,  "d",  "device",      I18S("device name"), NULL},
    { A_ARG, A_CHAR, "timestamp",      0,  1,  "ts", "timestamp",   I18S("Timestamp of the data (now if omitted)"), NULL},
    { A_ARG, A_CHAR, "jsonFile",       0,  1,  "J",  "jsonfile",    I18S("Name/path of a JSON file to read"), 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_SetCreateRequestMessageFn(o, _createRequestMessage);
  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)
{
  AQH_MESSAGE *msg;
  GWEN_DB_NODE *dbArgs;
  const char *valueName;
  const char *valueUnits;
  const char *valueData;
  const char *deviceName;
  const char *valueTimestamp;
  uint64_t timestampToSend;
  double dataToSend;
  const char *jsonFile;
  GWEN_JSON_ELEM *jRoot=NULL;
  AQH_VALUE *v;
  int rv;

  dbArgs=AQH_ToolClient_GetDbLocalArgs(o);
  jsonFile=GWEN_DB_GetCharValue(dbArgs, "jsonFile", 0, NULL);
  deviceName=GWEN_DB_GetCharValue(dbArgs, "device", 0, NULL);
  valueName=GWEN_DB_GetCharValue(dbArgs, "valueName", 0, NULL);
  valueUnits=GWEN_DB_GetCharValue(dbArgs, "valueUnits", 0, NULL);
  valueTimestamp=GWEN_DB_GetCharValue(dbArgs, "timestamp", 0, NULL);
  valueData=GWEN_DB_GetCharValue(dbArgs, "value", 0, NULL);
  if (!(valueName && *valueName)) {
    DBG_ERROR(NULL, "ERROR: Missing value name");
    return NULL;
  }

  if (!(valueData && *valueData)) {
    DBG_ERROR(NULL, "ERROR: Missing data");
    return NULL;
  }

  if (valueTimestamp && *valueTimestamp) {
    unsigned long int x;

    if (1!=sscanf("%lu", valueTimestamp, &x)) {
      DBG_ERROR(NULL, "ERROR: Invalid timestamp");
      return NULL;
    }
    timestampToSend=(uint64_t) x;
  }
  else
    timestampToSend=(uint64_t) time(NULL);

  if (jsonFile && *jsonFile) {
    const char *s;

    jRoot=_readJsonFile(jsonFile);
    if (jRoot==NULL) {
      DBG_ERROR(NULL, "ERROR: Error reading JSON file \"%s\"", jsonFile);
      return NULL;
    }
  
    if (valueData[0]=='@') {
      GWEN_JSON_ELEM *j;
  
      j=GWEN_JsonElement_GetElementByPath(jRoot, valueData+1, GWEN_PATH_FLAGS_PATHMUSTEXIST);
      if (j==NULL) {
        DBG_ERROR(NULL, "ERROR: Path \"%s\" not found in JSON file \"%s\"", valueData+1, jsonFile);
        GWEN_JsonElement_free(jRoot);
        return NULL;
      }
  
      s=GWEN_JsonElement_GetData(j);
      if (!(s && *s)) {
        DBG_ERROR(NULL, "ERROR: Path \"%s\" in JSON file \"%s\" has no data", valueData+1, jsonFile);
        GWEN_JsonElement_free(jRoot);
        return NULL;
      }
      valueData=s;
    }
  
    if (valueUnits) {
      if (valueUnits[0]=='@') {
        GWEN_JSON_ELEM *j;
  
        j=GWEN_JsonElement_GetElementByPath(jRoot, valueUnits+1, GWEN_PATH_FLAGS_PATHMUSTEXIST);
        if (j==NULL) {
          DBG_ERROR(NULL, "ERROR: Path \"%s\" not found in JSON file \"%s\"", valueUnits+1, jsonFile);
          return NULL;
        }
        s=GWEN_JsonElement_GetData(j);
        if (!(s && *s)) {
          DBG_ERROR(NULL, "ERROR: Path \"%s\" in JSON file \"%s\" has no data", valueUnits+1, jsonFile);
          return NULL;
        }
        valueUnits=s;
      }
    }
  } /* if json */

  rv=GWEN_Text_StringToDouble(valueData, &dataToSend);
  if (rv<0) {
    DBG_ERROR(NULL, "ERROR: Invalid data");
    GWEN_JsonElement_free(jRoot);
    return NULL;
  }

  v=AQH_Value_new();
  AQH_Value_SetName(v, valueName);
  AQH_Value_SetValueUnits(v, valueUnits);
  AQH_Value_SetDeviceName(v, deviceName);

  msg=AQH_IpcdMessageMultiData_newForOne(AQH_MSGTYPE_IPC_DATA_UPDATEDATA, msgId, 0, 0, v, timestampToSend, dataToSend);
  AQH_Value_free(v);
  GWEN_JsonElement_free(jRoot);
  return msg;
}



GWEN_JSON_ELEM *_readJsonFile(const char *filename)
{
  GWEN_BUFFER *buf;
  int rv;
  GWEN_JSON_ELEM *j;

  buf=GWEN_Buffer_new(0, 256, 0, 1);
  rv=GWEN_SyncIo_Helper_ReadFile(filename, buf);
  if (rv<0) {
    DBG_ERROR(NULL, "Error reading file \"%s\" (%d)", filename, rv);
    GWEN_Buffer_free(buf);
    return NULL;
  }

  j=GWEN_JsonElement_fromString(GWEN_Buffer_GetStart(buf));
  GWEN_Buffer_free(buf);
  if (j==NULL) {
    DBG_ERROR(NULL, "Invalid or no JSON data in file \"%s\"", filename);
    return NULL;
  }

  return j;
}



