/****************************************************************************
 * 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 "aqhome/msg/ipc/nodes/m_ipcn_forward.h"
#include "aqhome/msg/ipc/m_ipc_tag16.h"
#include "aqhome/msg/ipc/nodes/m_ipcn.h"
#include "aqhome/msg/ipc/m_ipc.h"

#include <gwenhywfar/text.h>
#include <gwenhywfar/tag16.h>
#include <gwenhywfar/buffer.h>



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



/* ------------------------------------------------------------------------------------------------
 * implementation
 * ------------------------------------------------------------------------------------------------
 */

AQH_MESSAGE *AQH_IpcnMessageForward_new(uint16_t code, uint32_t msgId, uint32_t refMsgId,
                                        const uint8_t *ptr, uint32_t len)
{
  AQH_MESSAGE *msg;
  GWEN_BUFFER *buf;

  buf=GWEN_Buffer_new(0, 256, 0, 1);

  GWEN_Tag16_WriteTagToBuffer(AQH_MSGNODE_FORWARD_TAGS_MSG, ptr, len, buf);

  msg=AQH_IpcMessage_new(AQH_IPC_PROTOCOL_NODES_ID, AQH_IPC_PROTOCOL_NODES_VERSION, code, msgId, refMsgId,
                         GWEN_Buffer_GetUsedBytes(buf), (const uint8_t*) GWEN_Buffer_GetStart(buf));
  GWEN_Buffer_free(buf);
  return msg;
}



void AQH_IpcnMessageForward_DumpToBuffer(const AQH_MESSAGE *msg, const GWEN_TAG16_LIST *tagList, GWEN_BUFFER *dbuf, const char *sText)
{
  const GWEN_TAG16 *tag;
  const uint8_t *ptr;
  uint32_t len;

  tag=tagList?GWEN_Tag16_List_FindFirstByTagType(tagList, AQH_MSGNODE_FORWARD_TAGS_MSG):NULL;
  ptr=tag?GWEN_Tag16_GetTagData(tag):NULL;
  len=tag?GWEN_Tag16_GetTagLength(tag):0;

  GWEN_Buffer_AppendArgs(dbuf, "FORWARD(%s) %s (code=%d, protocol=%d, protocol version=%d)\n",
                         AQH_IpcnMessage_MsgTypeToChar(AQH_IpcMessage_GetCode(msg)),
                         sText?sText:"",
                         AQH_IpcMessage_GetCode(msg),
                         AQH_IpcMessage_GetProtoId(msg),
                         AQH_IpcMessage_GetProtoVersion(msg));
  if (ptr && len) {
    GWEN_Text_DumpString2Buffer((const char*)ptr, len, dbuf, 2);
    GWEN_Buffer_AppendByte(dbuf, '\n');
  }
}






