/****************************************************************************
 * 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 "./utils.h"

#include "aqhome/msg/ipc/m_ipc.h"
#include "aqhome/msg/ipc/data/m_ipcd.h"
#include "aqhome/msg/ipc/nodes/m_ipcn.h"
#include "aqhome/msg/ipc/nodes/m_ipcn_setaccmsggrps.h"
#include "aqhome/ipc2/tcp_object.h"
#include "aqhome/ipc2/ipc_client.h"
#include "aqhome/dataclient/client.h"


#include <gwenhywfar/debug.h>
#include <gwenhywfar/timestamp.h>
#include <gwenhywfar/db.h>

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


#define UTILS_IPC_ENDPOINT_DEFAULT_MSGSIZE 4096



AQH_OBJECT *Utils2_SetupBrokerClientEndpoint(AQH_EVENT_LOOP *eventLoop, GWEN_DB_NODE *dbArgs, uint32_t flags)
{
  const char *brokerAddress;
  int brokerPort;

  brokerAddress=GWEN_DB_GetCharValue(dbArgs, "brokerAddress", 0, NULL);
  if (!(brokerAddress && *brokerAddress))
    brokerAddress=GWEN_DB_GetCharValue(dbArgs, "ConfigFile/brokerAddress", 0, "127.0.0.1");

  brokerPort=GWEN_DB_GetIntValue(dbArgs, "brokerPort", 0, -1);
  if (brokerPort<0)
    brokerPort=GWEN_DB_GetIntValue(dbArgs, "ConfigFile/brokerPort", 0, 45456);

  if (brokerAddress && *brokerAddress && brokerPort) {
    AQH_OBJECT *ep;
    int fd;

    fd=AQH_TcpObject_CreateConnectedSocket(brokerAddress, brokerPort);
    if (fd<0) {
      DBG_ERROR(NULL, "Error connecting to broker server %s:%d", brokerAddress, brokerPort);
      return NULL;
    }

    ep=AQH_IpcClientObject_new(eventLoop, fd);
    assert(ep);
    AQH_Endpoint_AddFlags(ep, flags);
    return ep;
  }
  else {
    DBG_ERROR(NULL, "No server settings");
  }

  return NULL;
}



AQH_OBJECT *Utils2_SetupNodesClientEndpoint(AQH_EVENT_LOOP *eventLoop, GWEN_DB_NODE *dbArgs, uint32_t flags)
{
  const char *address;
  int port;

  address=GWEN_DB_GetCharValue(dbArgs, "tcpAddress", 0, NULL);
  if (!(address && *address))
    address=GWEN_DB_GetCharValue(dbArgs, "ConfigFile/nodesAddress", 0, "127.0.0.1");

  port=GWEN_DB_GetIntValue(dbArgs, "tcpPort", 0, -1);
  if (port<0)
    port=GWEN_DB_GetIntValue(dbArgs, "ConfigFile/nodesPort", 0, 45456);

  if (address && *address && port) {
    AQH_OBJECT *ep;
    int fd;

    DBG_INFO(NULL, "Connecting to nodes server %s:%d", address, port);
    fd=AQH_TcpObject_CreateConnectedSocket(address, port);
    if (fd<0) {
      DBG_ERROR(NULL, "Error connecting to nodes server %s:%d", address, port);
      return NULL;
    }
    DBG_INFO(NULL, "Connected to nodes server %s:%d", address, port);

    ep=AQH_IpcClientObject_new(eventLoop, fd);
    assert(ep);
    AQH_Endpoint_AddFlags(ep, flags);
    return ep;
  }
  else {
    DBG_ERROR(NULL, "No server settings");
  }

  return NULL;
}



int Utils_SendAcceptedMsgGroups(AQH_OBJECT *ep, uint32_t groups)
{
  AQH_MESSAGE *msgOut;

  msgOut=AQH_IpcnMessageSetAcceptedMsgGroups_new(AQH_MSGTYPE_IPC_NODES_SETACCMSGGRPS,
                                                 AQH_Endpoint_GetNextMessageId(ep),0,
                                                 groups);
  if (msgOut==NULL) {
    DBG_ERROR(NULL, "Error creating message");
    return GWEN_ERROR_GENERIC;
  }
  AQH_Endpoint_AddMsgOut(ep, msgOut);
  return 0;
}



void Utils_PrintDataPoints(const uint64_t *dataPoints, uint32_t numValues, const char *valueUnits)
{
  uint32_t i;
  
  for(i=0; i<numValues; i++) {
    uint64_t timestamp;
    union {double f; uint64_t i;} u;
  
    timestamp=*(dataPoints++);
    u.i=*(dataPoints++);

    Utils_PrintSingleDataPoint(timestamp, u.f, valueUnits);
  }
}



void Utils_PrintSingleDataPoint(uint64_t timestamp, double data, const char *valueUnits)
{
  GWEN_TIMESTAMP *ts;

  ts=GWEN_Timestamp_fromLocalTime((time_t) timestamp);
  if (ts)
    fprintf(stdout, "%04d/%02d/%02d-%02d:%02d:%02d\t%lf\t%s\t%lu\n",
            GWEN_Timestamp_GetYear(ts),
            GWEN_Timestamp_GetMonth(ts),
            GWEN_Timestamp_GetDay(ts),
            GWEN_Timestamp_GetHour(ts),
            GWEN_Timestamp_GetMinute(ts),
            GWEN_Timestamp_GetSecond(ts),
            data, valueUnits?valueUnits:"", (unsigned long) timestamp);
  else
    fprintf(stdout, "\t%lf\t%s\t%lu\n",
            data, valueUnits?valueUnits:"", (unsigned long) timestamp);
}



void Utils_PrintFormattedSingleDataPoint(const AQH_VALUE *v, uint64_t timestamp, double data, const char *tmpl)
{
  GWEN_DB_NODE *dbData;
  GWEN_TIMESTAMP *ts;

  dbData=GWEN_DB_Group_new("data");
  if (v) {
    GWEN_DB_NODE *dbValue;

    dbValue=GWEN_DB_Group_new("value");
    AQH_Value_toDb(v, dbValue);
    GWEN_DB_AddGroup(dbData, dbValue);
  }

  ts=GWEN_Timestamp_fromLocalTime((time_t) timestamp);
  if (ts) {
    GWEN_BUFFER *buf;
    GWEN_DB_NODE *dbDataPoint;

    dbDataPoint=GWEN_DB_Group_new("dataPoint");

    buf=GWEN_Buffer_new(0, 256, 0, 1);
    GWEN_Buffer_AppendArgs(buf, "%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));
    GWEN_DB_SetCharValue(dbDataPoint, GWEN_DB_FLAGS_OVERWRITE_VARS, "timestampAsDate", GWEN_Buffer_GetStart(buf));
    GWEN_Timestamp_free(ts);

    GWEN_Buffer_Reset(buf);
    GWEN_Buffer_AppendArgs(buf, "%lu", (unsigned long int) timestamp);
    GWEN_DB_SetCharValue(dbDataPoint, GWEN_DB_FLAGS_OVERWRITE_VARS, "timestampAsInt", GWEN_Buffer_GetStart(buf));

    GWEN_Buffer_Reset(buf);
    GWEN_Buffer_AppendArgs(buf, "%f", data);
    GWEN_DB_SetCharValue(dbDataPoint, GWEN_DB_FLAGS_OVERWRITE_VARS, "datapoint", GWEN_Buffer_GetStart(buf));
    GWEN_Buffer_Reset(buf);

    GWEN_DB_AddGroup(dbData, dbDataPoint);

    GWEN_Buffer_Reset(buf);
    GWEN_DB_ReplaceVars(dbData, tmpl, buf);
    fprintf(stdout, "%s\n", GWEN_Buffer_GetStart(buf));
    GWEN_Buffer_free(buf);
  }

  GWEN_DB_Group_free(dbData);
}



void Utils_PrintMeanData(const uint64_t *dataPoints, uint32_t numValues, const char *valueUnits)
{
  if (numValues) {
    uint32_t i;
    uint64_t timestamp=0;
    double total=0.0;

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

      timestamp=*(dataPoints++); /* use last timestamp encountered */
      u.i=*(dataPoints++);
      total+=u.f;
    }
    total=total/(double)numValues;
    Utils_PrintSingleDataPoint(timestamp, total, valueUnits);
  }
}



void Utils_PrintDiffData(const uint64_t *dataPoints, uint32_t numValues, const char *valueUnits)
{
  if (numValues) {
    if (numValues>1) {
      uint64_t timestamp=0;
      double valueFirst=0.0;
      double valueLast=0.0;
      double valueDiff=0.0;
      union {double f; uint64_t i;} u;

      /* ignore timestamp of first datapoint */
      u.i=dataPoints[1];
      valueFirst=u.f;

      timestamp=dataPoints[(numValues-1)*2];
      u.i=dataPoints[((numValues-1)*2)+1];
      valueLast=u.f;

      valueDiff=valueLast-valueFirst;

      Utils_PrintSingleDataPoint(timestamp, valueDiff, valueUnits);
    }
    else {
      uint64_t timestamp;
      union {double f; uint64_t i;} u;

      timestamp=dataPoints[0];
      u.i=dataPoints[1];

      Utils_PrintSingleDataPoint(timestamp, u.f, valueUnits);
    }
  }
}



void Utils_PrintDevice(const AQH_DEVICE *device, int printHeader)
{
  GWEN_TIMESTAMP *ts;
  uint64_t deviceId;
  const char *deviceNameForSystem;
  const char *deviceNameForGui;
  const char *roomName;
  const char *location;
  const char *description;
  uint64_t timestamp;

  deviceId=AQH_Device_GetId(device);
  deviceNameForSystem=AQH_Device_GetNameForSystem(device);
  deviceNameForGui=AQH_Device_GetNameForGui(device);
  roomName=AQH_Device_GetRoomName(device);
  location=AQH_Device_GetLocation(device);
  description=AQH_Device_GetDescription(device);
  timestamp=AQH_Device_GetTimestampCreation(device);
  ts=timestamp?GWEN_Timestamp_fromLocalTime((time_t) timestamp):NULL;

  if (printHeader)
    fprintf(stdout, "ID\tName\tCreation Date\tGUI Name\tRoom\tLocation\tDescription\n");


  if (ts)
    fprintf(stdout, "%lu\t%s\t%04d/%02d/%02d-%02d:%02d:%02d\t%s\t%s\t%s\t%s\n",
            deviceId,
            deviceNameForSystem,
            GWEN_Timestamp_GetYear(ts),
            GWEN_Timestamp_GetMonth(ts),
            GWEN_Timestamp_GetDay(ts),
            GWEN_Timestamp_GetHour(ts),
            GWEN_Timestamp_GetMinute(ts),
            GWEN_Timestamp_GetSecond(ts),
            deviceNameForGui?deviceNameForGui:"",
            roomName?roomName:"",
            location?location:"",
            description?description:"");
  else
    fprintf(stdout, "%lu\t%s\t\t%s\t%s\t%s\t%s\n",
            deviceId,
            deviceNameForSystem,
            deviceNameForGui?deviceNameForGui:"",
            roomName?roomName:"",
            location?location:"",
            description?description:"");
}



AQH_DEVICE *Utils_DeviceFromArgs(GWEN_DB_NODE *dbArgs)
{
  AQH_DEVICE *device;

  device=AQH_Device_new();
  AQH_Device_SetNameForSystem(device, GWEN_DB_GetCharValue(dbArgs, "device", 0, NULL));
  AQH_Device_SetNameForGui(device, GWEN_DB_GetCharValue(dbArgs, "nameForGui", 0, NULL));
  AQH_Device_SetRoomName(device, GWEN_DB_GetCharValue(dbArgs, "roomName", 0, NULL));
  AQH_Device_SetLocation(device, GWEN_DB_GetCharValue(dbArgs, "location", 0, NULL));
  AQH_Device_SetDescription(device, GWEN_DB_GetCharValue(dbArgs, "description", 0, NULL));

  return device;
}



void Utils_PrintValue(const AQH_VALUE *value, int printHeader)
{
  uint64_t valueId;
  const char *valueName;
  const char *valueUnits;

  valueId=AQH_Value_GetId(value);
  valueName=AQH_Value_GetNameForSystem(value);
  valueUnits=AQH_Value_GetValueUnits(value);

  if (printHeader)
    fprintf(stdout, "ID\tName\tUnits\n");
  fprintf(stdout, "%lu\t%s\t%s\n",
          (unsigned long int) valueId,
          valueName?valueName:"",
          valueUnits?valueUnits:"");
}



uint64_t Utils_GetTimeStampFromString(const char *s)
{
  if (s && *s) {
    if (*s=='-') {
      uint64_t x=0;
      uint64_t now=time(NULL);

      s++;
      while(*s && isdigit(*s)) {
        unsigned int i;

        i=*(s++)-'0';
        x*=10;
        x+=i;
      }
      if (*s) {
        switch(*s) {
        case 0:
        case 'm': x*=60; break;
        case 'h': x*=(60*60); break;
        case 'd': x*=(60*60*24); break;
        case 'w': x*=(60*60*24*7); break;
        case 'M': x*=(60*60*24*30); break;
        case 'y': x*=(60*60*24*365); break;
        default:  break;
        }
      }
      return (now-x);
    }
    if (*s=='@') {
      int y, m, d, H, M, S;

      if (6==sscanf(s+1, "%d/%d/%d-%d:%d:%d", &y, &m, &d, &H, &M, &S)) {
        GWEN_TIMESTAMP *ts;
        uint64_t x=0;

        ts=GWEN_Timestamp_new(y, m, d, H, M, S);
        x=GWEN_Timestamp_toTimeT(ts);
        GWEN_Timestamp_free(ts);
        return x;
      }
      else {
        DBG_ERROR(NULL, "Invalid timespec [%s], expected: @YYYY/MM/DD-HH:MM:SS", s);
        return (uint64_t) (-1);
      }
    }
    else {
      unsigned long int x;

      if (1!=sscanf(s, "%lu", &x)) {
        DBG_ERROR(NULL, "ERROR: Invalid timestamp");
        return (uint64_t) (-1);
      }
      return (uint64_t) x;
    }
  }
  return 0;
}






