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

#include "aqhome/dataclient/client.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_getdata.h"
#include "aqhome/msg/ipc/data/m_ipcd_multidata.h"
#include "aqhome/dataclient/client.h"

#include <aqdiagram/graph/timegraph.h>
#include <aqdiagram/graph/w_graph.h>
#include <aqdiagram/draw/context_cairo.h>
#include <aqdiagram/data/date.h>
#include <aqdiagram/data/floatingavg.h>

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



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

static int _createGraph(AQH_DATACLIENT *dc);

static AQDG_GRAPH_DATAPAIR_LIST *_createDataPairListFromDataPoints(const uint64_t *dataPoints, uint64_t numValues);
static AQDG_GRAPH_DATAPAIR_LIST *_requestDataPairList(AQH_DATACLIENT *dc, const char *valueName,
                                                      uint64_t num, uint64_t tsBegin, uint64_t tsEnd);




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

int AQH_Tool_ImgPeriodData(GWEN_DB_NODE *dbGlobalArgs, int argc, char **argv)
{
  AQH_EVENT_LOOP *eventLoop;
  AQH_DATACLIENT *dc;
  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_INT,  "numOfDatapoints",     0,  1,  "n",  NULL,          I18S("Get up to n datapoints"), NULL},
    { A_ARG, A_CHAR, "tsBegin",             0,  1,  "tb", "tsbegin",     I18S("Timestamp range begin"), NULL},
    { A_ARG, A_CHAR, "tsEnd",               0,  1,  "te", "tsend",       I18S("Timestamp range end"), NULL},
    { A_ARG, A_CHAR, "imgFile",             1,  1,  "F",  NULL,          I18S("Image path"), NULL},
    { A_ARG, A_INT,  "imgWidth",            0,  1,  "W",  NULL,          I18S("Image width"), NULL},
    { A_ARG, A_INT,  "imgHeight",           0,  1,  "H",  NULL,          I18S("Image height"), NULL},
    { A_ARG, A_CHAR, "upperLimit",          0,  1,  "U",  NULL,          I18S("Upper limit for y axis"), NULL},
    { A_ARG, A_CHAR, "lowerLimit",          0,  1,  "L",  NULL,          I18S("Lower limit for y axis"), NULL},
    { A_ARG, A_INT,  "precision",           0,  1,  "yp", NULL,          I18S("Y axis Data Precision (default: 2)"), NULL},
    { A_ARG, A_CHAR, "graphTitle",          0,  1,  "gt", NULL,          I18S("Graph title"), NULL},
    { A_ARG, A_CHAR, "curveSpec",           1,  64, "G",  NULL,          I18S("Curve specification"), NULL},
    { A_END, A_INT,  "help",                0,  0,  "h",  "help",        I18S("Show this help screen"), NULL}
  };

  eventLoop=AQH_EventLoop_new();
  dc=AQH_DataClient_new(eventLoop, AQH_IPC_PROTOCOL_DATA_ID, AQH_IPC_PROTOCOL_DATA_VERSION);

  rv=AQH_DataClient_ReadLocalArgs(dc, dbGlobalArgs, args, argc, argv);
  if (rv!=0) {
    DBG_ERROR(NULL, "here (%d)", rv);
    AQH_DataClient_free(dc);
    AQH_EventLoop_free(eventLoop);
    return 2;
  }

  rv=AQH_DataClient_ConnectWithArgs(dc, 0);
  if (rv<0) {
    DBG_ERROR(NULL, "Error connecting (%d)", rv);
    AQH_DataClient_free(dc);
    AQH_EventLoop_free(eventLoop);
    return 2;
  }

  rv=_createGraph(dc);
  if (rv<0) {
    DBG_ERROR(NULL, "Error running (%d)", rv);
    AQH_DataClient_free(dc);
    AQH_EventLoop_free(eventLoop);
    return 2;
  }

  AQH_DataClient_free(dc);
  AQH_EventLoop_free(eventLoop);
  return 0;
}



int _createGraph(AQH_DATACLIENT *dc)
{
  GWEN_DB_NODE *dbLocalArgs;
  int numDataPoints;
  uint64_t tsBegin;
  uint64_t tsEnd;
  const char *imgFile;
  int imgWidth;
  int imgHeight;
  int precision;
  const char *s;
  uint32_t tickFlags=0;
  double upperLimit;
  double lowerLimit;
  const char *graphTitle;
  AQDG_GRAPH *g;
  AQDG_DRAW_CONTEXT *drawContext;
  AQDG_OBJECT *graphObject;
  int i;

  dbLocalArgs=AQH_DataClient_GetDbLocalArgs(dc);
  numDataPoints=GWEN_DB_GetIntValue(dbLocalArgs, "numOfDatapoints", 0, 10000); /* remove later */
  imgFile=GWEN_DB_GetCharValue(dbLocalArgs, "imgFile", 0, NULL);
  imgWidth=GWEN_DB_GetIntValue(dbLocalArgs, "imgWidth", 0, 800);
  imgHeight=GWEN_DB_GetIntValue(dbLocalArgs, "imgHeight", 0, 600);
  precision=GWEN_DB_GetIntValue(dbLocalArgs, "precision", 0, 2);
  graphTitle=GWEN_DB_GetCharValue(dbLocalArgs, "graphTitle", 0, NULL);

  tsBegin=Utils_GetTimeStampFromString(GWEN_DB_GetCharValue(dbLocalArgs, "tsBegin", 0, NULL));
  if (tsBegin==(uint64_t) (-1)) {
    DBG_ERROR(NULL, "Bad begin timestamp");
    return 1;
  }
  tsEnd=Utils_GetTimeStampFromString(GWEN_DB_GetCharValue(dbLocalArgs, "tsEnd", 0, NULL));
  if (tsEnd==(uint64_t) (-1)) {
    DBG_ERROR(NULL, "Bad end timestamp");
    return 1;
  }

  s=GWEN_DB_GetCharValue(dbLocalArgs, "upperLimit", 0, NULL);
  if (s && *s) {
    if (1==sscanf(s, "%lf", &upperLimit))
      tickFlags|=AQDG_TIMEGRAPH_SETUPTICKS_FLAGS_MAXY;
    else {
      fprintf(stderr, "Invalid upperLimit (%s)\n", s);
      return 1;
    }
  }

  s=GWEN_DB_GetCharValue(dbLocalArgs, "lowerLimit", 0, NULL);
  if (s && *s) {
    if (1==sscanf(s, "%lf", &lowerLimit))
      tickFlags|=AQDG_TIMEGRAPH_SETUPTICKS_FLAGS_MINY;
    else {
      fprintf(stderr, "Invalid lowerLimit (%s)\n", s);
      return 1;
    }
  }

  g=AQDG_TimeGraph_new(graphTitle?graphTitle:NULL, NULL, "Value", NULL, precision);

  for (i=0; i<16; i++) {
    const char *curveSpec;

    curveSpec=GWEN_DB_GetCharValue(dbLocalArgs, "curveSpec", i, NULL);
    if (curveSpec) {
      GWEN_STRINGLIST *sl;
      char delim[2];

      delim[0]=curveSpec[0];
      delim[1]=0;
      sl=GWEN_StringList_fromString2(curveSpec+1, delim, 0, GWEN_TEXT_FLAGS_CHECK_BACKSLASH);
      if (sl) {
        const char *sValue;
        const char *sLabel;
        const char *sModifier;

        sValue=GWEN_StringList_StringAt(sl, 0);
        sLabel=GWEN_StringList_StringAt(sl, 1);
        sModifier=GWEN_StringList_StringAt(sl, 2);
        DBG_DEBUG(NULL, "Value: %s, Label: %s, Modifier: %s", sValue?sValue:"", sLabel?sLabel:"", sModifier?sModifier:"");

        if (sValue && *sValue) {
          AQDG_GRAPH_DATAPAIR_LIST *dpList;

          DBG_DEBUG(NULL, "Requesting data for %s", sValue);
          dpList=_requestDataPairList(dc, sValue, numDataPoints, tsBegin, tsEnd);
          if (dpList)
            AQDG_TimeGraph_ModifyDataAndAddCurve(g, sLabel?sLabel:sValue, sModifier, dpList);
        }
        GWEN_StringList_free(sl);
      }
    }
    else
      break;
  }

  AQDG_TimeGraph_SetupTicks(g, tickFlags, lowerLimit, upperLimit);

  drawContext=AQDG_Draw_ContextCairo_Png_new(imgFile, imgWidth, imgHeight);
  graphObject=AQDG_GraphWidget_new(NULL, AQDG_OBJECT_OPTIONS_STRETCHX | AQDG_OBJECT_OPTIONS_STRETCHY, drawContext);
  AQDG_Object_SetWidth(graphObject, imgWidth);
  AQDG_Object_SetHeight(graphObject, imgHeight);

  AQDG_GraphWidget_SetupDefaultPens(graphObject);
  AQDG_GraphWidget_SetupDefaultFonts(graphObject);

  AQDG_GraphWidget_FinishWithGraph(graphObject, g);

  return 0;
}



AQDG_GRAPH_DATAPAIR_LIST *_requestDataPairList(AQH_DATACLIENT *dc, const char *valueName,
                                               uint64_t num, uint64_t tsBegin, uint64_t tsEnd)
{
  uint64_t *dataPoints;
  uint64_t recvdNum;

  dataPoints=malloc(num*sizeof(uint64_t)*2);

  recvdNum=AQH_DataClient_GetPeriodData(dc, valueName, dataPoints, num, tsBegin, tsEnd);
  if (recvdNum>0) {
    AQDG_GRAPH_DATAPAIR_LIST *dpList;

    dpList=_createDataPairListFromDataPoints(dataPoints, recvdNum);
    free(dataPoints);
    return dpList;
  }
  else {
    free(dataPoints);
    return NULL;
  }
}



AQDG_GRAPH_DATAPAIR_LIST *_createDataPairListFromDataPoints(const uint64_t *dataPoints, uint64_t numValues)
{
  AQDG_GRAPH_DATAPAIR_LIST *dpList;
  uint64_t i;

  DBG_DEBUG(NULL, "Got %d datapoints", (int) numValues);
  dpList=AQDG_Graph_DataPair_List_new();
  for(i=0; i<numValues; i++) {
    AQDG_GRAPH_DATAPAIR *dp;
    double timestamp;
    union {double f; uint64_t i;} u;
  
    timestamp=(double)(*(dataPoints++));
    u.i=*(dataPoints++);
    dp=AQDG_Graph_DataPair_new();
    AQDG_Graph_DataPair_SetValueX(dp, timestamp);
    AQDG_Graph_DataPair_SetValueY(dp, u.f);
    AQDG_Graph_DataPair_List_Add(dp, dpList);
  }
  AQDG_Graph_DataPair_List_SortByValueX(dpList, 1);
  return dpList;
}






