/****************************************************************************
 * 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 <aqhome/ipc/data/msg_data_getdata.h>
#include <aqhome/ipc/data/ipc_data.h>
#include <aqhome/ipc/msg_ipc_tag16.h>

#include <gwenhywfar/msg.h>
#include <gwenhywfar/buffer.h>

#include <gwenhywfar/debug.h>
#include <gwenhywfar/msg_ipc.h>



#define AQH_MSGDATA_GETDATA_MINSIZE GWEN_MSGIPC_OFFS_PAYLOAD




GWEN_MSG *AQH_GetDataDataIpcMsg_new(uint16_t code, const char *valueName, uint64_t tsBegin, uint64_t tsEnd, uint64_t num)
{
  GWEN_MSG *msg;
  GWEN_BUFFER *buf;

  buf=GWEN_Buffer_new(0, 256, 0, 1);
  if (valueName && *valueName)
    GWEN_Tag16_WriteStringTagToBuffer(AQH_MSGDATA_GETDATA_TAGS_NAME, valueName, buf);
  GWEN_Tag16_WriteUint64TagToBuffer(AQH_MSGDATA_GETDATA_TAGS_BEGIN, tsBegin, buf);
  GWEN_Tag16_WriteUint64TagToBuffer(AQH_MSGDATA_GETDATA_TAGS_END, tsEnd, buf);
  GWEN_Tag16_WriteUint64TagToBuffer(AQH_MSGDATA_GETDATA_TAGS_NUM, num, buf);

  msg=AQH_Tag16IpcMsg_new(AQH_IPC_PROTOCOL_DATA_ID, AQH_IPC_PROTOCOL_DATA_VERSION, code,
			  GWEN_Buffer_GetUsedBytes(buf), (const uint8_t*) GWEN_Buffer_GetStart(buf));
  GWEN_Buffer_free(buf);
  return msg;
}



void AQH_GetDataDataIpcMsg_Parse(GWEN_MSG *msg, int doCopy)
{
  AQH_Tag16IpcMsg_ExtendAndParse(msg, doCopy);
}



void AQH_GetDataDataIpcMsg_DumpToBuffer(const GWEN_MSG *msg, GWEN_BUFFER *dbuf, const char *sText)
{
  if (GWEN_Msg_GetBytesInBuffer(msg)>=AQH_MSGDATA_GETDATA_MINSIZE) {
    char *valueName=NULL;
    uint64_t tsBegin=0;
    uint64_t tsEnd=0;

    valueName=AQH_Tag16IpcMsg_GetTagDataAsNewString(msg, AQH_MSGDATA_GETDATA_TAGS_NAME, NULL);
    tsBegin=AQH_Tag16IpcMsg_GetTagDataAsUint64(msg, AQH_MSGDATA_GETDATA_TAGS_BEGIN, 0);
    tsEnd=AQH_Tag16IpcMsg_GetTagDataAsUint64(msg, AQH_MSGDATA_GETDATA_TAGS_END, 0);

    GWEN_Buffer_AppendArgs(dbuf,
                           "GETDATA (code=%d, proto=%d, proto version=%d, name=%s, tsBegin=%lu, tsEnd=%lu)\n",
                           GWEN_IpcMsg_GetCode(msg),
                           GWEN_IpcMsg_GetProtoId(msg),
                           GWEN_IpcMsg_GetProtoVersion(msg),
                           valueName?valueName:"<empty>",
                           (unsigned long int) tsBegin,
                           (unsigned long int) tsEnd);
    free(valueName);
  }
}







