/****************************************************************************
 * 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/msg_setaccmsggrps.h"

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




AQH_MSG *AQH_MsgSetAcceptedMsgGroups_new(uint8_t destAddr, uint32_t groups)
{
  AQH_MSG *msg;

  msg=AQH_Msg_new();
  AQH_Msg_AddByte(msg, destAddr);                                 /* DESTADDR */
  AQH_Msg_AddByte(msg, 2+4);                                      /* MSGLEN: srcAddr(1), msgType(1), groups (4) */
  AQH_Msg_AddByte(msg, AQH_MSG_TYPE_NET_SET_ACCEPTED_MSGGROUPS);  /* MSGTYPE */
  AQH_Msg_AddByte(msg, 0);                                        /* SRCADDR (admin, no src address needed) */
  AQH_Msg_AddByte(msg, groups & 0xff);                            /* 4 bytes remaining payload */
  AQH_Msg_AddByte(msg, (groups>>8) & 0xff);
  AQH_Msg_AddByte(msg, (groups>>16) & 0xff);
  AQH_Msg_AddByte(msg, (groups>>24) & 0xff);
  AQH_Msg_AddChecksum(msg);
  AQH_Msg_RewindCurrentPos(msg);

  return msg;
}



uint32_t AQH_MsgSetAcceptedMsgGroups_GetMsgGroups(const AQH_MSG *msg)
{
  if ((AQH_Msg_GetMsgType(msg)==AQH_MSG_TYPE_NET_SET_ACCEPTED_MSGGROUPS) &&
      (AQH_Msg_GetBytesInBuffer(msg)>=AQH_MSG_SETACCMSGGRPS_MINSIZE)) {
    const uint8_t *ptr;

    ptr=AQH_Msg_GetConstBuffer(msg)+AQH_MSG_OFFS_ALL_DATA_BEGIN+AQH_MSG_OFFS_SETACCMSGGRPS_GRPS;
    return (uint32_t)(ptr[0])+(ptr[1]<<8)+(ptr[2]<<16)+(ptr[3]<<24);
  }
  return 0;
}



void AQH_MsgSetAcceptedMsgGroups_DumpToBuffer(const AQH_MSG *msg, GWEN_BUFFER *dbuf, const char *sText)
{
  if ((AQH_Msg_GetMsgType(msg)==AQH_MSG_TYPE_NET_SET_ACCEPTED_MSGGROUPS) &&
      (AQH_Msg_GetBytesInBuffer(msg)>=AQH_MSG_SETACCMSGGRPS_MINSIZE)) {
    GWEN_Buffer_AppendArgs(dbuf,
                           "0x%02x->0x%02x: ACCEPTED_MSG_GROUPS %s (groups=0x%08x)\n",
                           AQH_Msg_GetSourceAddress(msg),
                           AQH_Msg_GetDestAddress(msg),
                           sText,
                           (unsigned int) AQH_MsgSetAcceptedMsgGroups_GetMsgGroups(msg));

  }
}



