/****************************************************************************
 * 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/nodes/msg_ipc_forward.h>

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

#include <gwenhywfar/misc.h>
#include <gwenhywfar/list.h>
#include <gwenhywfar/error.h>
#include <gwenhywfar/debug.h>
#include <gwenhywfar/text.h>
#include <gwenhywfar/msg_ipc.h>



#define AQH_MSG_OFFS_FORWARD_MSG        (GWEN_MSGIPC_OFFS_PAYLOAD+0)

#define AQH_MSG_FORWARD_MINSIZE (AQH_MSG_OFFS_FORWARD_MSG+AQH_MSG_OFFS_ALL_DATA_BEGIN)



GWEN_MSG *AQH_ForwardIpcMsg_new(uint16_t code, const uint8_t *ptr, uint32_t len)
{
  return GWEN_IpcMsg_new(AQH_IPC_PROTOCOL_NODES_ID, AQH_IPC_PROTOCOL_NODES_VERSION, code, len, ptr);
}



const uint8_t *AQH_ForwardIpcMsg_GetMsgPtr(const GWEN_MSG *msg)
{
  if (GWEN_Msg_GetBytesInBuffer(msg)>=AQH_MSG_FORWARD_MINSIZE)
    return GWEN_Msg_GetConstBuffer(msg)+AQH_MSG_OFFS_FORWARD_MSG;
  return NULL;
}



uint32_t AQH_ForwardIpcMsg_GetMsgLen(const GWEN_MSG *msg)
{
  uint32_t len;

  len=GWEN_Msg_GetBytesInBuffer(msg);
  if (len>AQH_MSG_FORWARD_MINSIZE) {
    return len-AQH_MSG_OFFS_FORWARD_MSG;
  }
  return 0;
}


GWEN_MSG *AQH_ForwardIpcMsg_GetCopyOfNodeMsg(const GWEN_MSG *msg)
{
  return GWEN_Msg_fromBytes(AQH_ForwardIpcMsg_GetMsgPtr(msg), AQH_ForwardIpcMsg_GetMsgLen(msg));
}



void AQH_ForwardIpcMsg_DumpToBuffer(const GWEN_MSG *msg, GWEN_BUFFER *dbuf, const char *sText)
{
  if (GWEN_Msg_GetBytesInBuffer(msg)>=AQH_MSG_FORWARD_MINSIZE) {
    const uint8_t *ptr;
    uint32_t len;

    ptr=AQH_ForwardIpcMsg_GetMsgPtr(msg);
    len=AQH_ForwardIpcMsg_GetMsgLen(msg);

    GWEN_Buffer_AppendArgs(dbuf, "FORWARD (code=%d, protocol=%d, protocol version=%d)\n",
                           GWEN_IpcMsg_GetCode(msg),
                           GWEN_IpcMsg_GetProtoId(msg),
                           GWEN_IpcMsg_GetProtoVersion(msg));
    if (ptr && len) {
      GWEN_Text_DumpString2Buffer((const char*)ptr, len, dbuf, 2);
      GWEN_Buffer_AppendByte(dbuf, '\n');
    }
  }
}







