/****************************************************************************
 * This file is part of the project AqHome.
 * AqHome (c) by 2024 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_set.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>
#include <gwenhywfar/text.h>
#include <gwenhywfar/tag16.h>

#include <string.h>


#define AQH_MSGDATA_SET_MINSIZE GWEN_MSGIPC_OFFS_PAYLOAD



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



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

GWEN_MSG *AQH_SetDataIpcMsg_new(uint16_t code, const AQH_VALUE *value, const char *data)
{
  GWEN_MSG *msg;
  GWEN_BUFFER *buf;
  int rv;

  buf=GWEN_Buffer_new(0, 256, 0, 1);
  rv=AQH_DataIpc_WriteValueAsTagToBuffer(AQH_MSGDATA_SET_TAGS_VALUE, value, buf);
  if (rv<0) {
    DBG_INFO(AQH_LOGDOMAIN, "here (%d)", rv);
    GWEN_Buffer_free(buf);
    return NULL;
  }
  if (data && *data)
    GWEN_Tag16_WriteStringTagToBuffer(AQH_MSGDATA_SET_TAGS_DATA, data, 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_SetDataIpcMsg_Parse(GWEN_MSG *msg, int doCopy)
{
  AQH_Tag16IpcMsg_ExtendAndParse(msg, doCopy);
}



AQH_VALUE *AQH_SetDataIpcMsg_ReadValue(const GWEN_MSG *msg)
{
  return AQH_DataIpc_ReadValueFromTagList(AQH_Tag16IpcMsg_GetTags(msg), AQH_MSGDATA_SET_TAGS_VALUE);
}


char *AQH_SetDataIpcMsg_ReadData(const GWEN_MSG *msg)
{
  return AQH_Tag16IpcMsg_GetTagDataAsNewString(msg, AQH_MSGDATA_SET_TAGS_DATA, NULL);
}



void AQH_SetDataIpcMsg_DumpToBuffer(const GWEN_MSG *msg, GWEN_BUFFER *dbuf, const char *sText)
{
  if (GWEN_Msg_GetBytesInBuffer(msg)>=AQH_MSGDATA_SET_MINSIZE) {
    GWEN_Buffer_AppendArgs(dbuf,
                           "SET (code=%d, proto=%d, proto version=%d)\n",
                           GWEN_IpcMsg_GetCode(msg),
                           GWEN_IpcMsg_GetProtoId(msg),
                           GWEN_IpcMsg_GetProtoVersion(msg));
  }
}






