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

#include <gwenhywfar/debug.h>



GWEN_MSG *GWEN_PubResponseMqttMsg_new(uint8_t typeAndFlags, uint16_t pkgId)
{
  uint8_t data[2];
  GWEN_MSG *msg;

  data[0]=pkgId>>8 & 0xff;
  data[1]=pkgId & 0xff;

  msg=GWEN_MqttMsg_new(AQH_MQTTMSG_MSGTYPE_CONNACK, 2, data);
  if (msg==NULL) {
    DBG_INFO(AQH_LOGDOMAIN, "here");
    return NULL;
  }
  return msg;
}



uint16_t AQH_PubResponseMqttMsg_GetPacketId(const GWEN_MSG *msg)
{
  const uint8_t *msgPtr;
  uint32_t msgLen;

  msgPtr=GWEN_Msg_GetConstBuffer(msg);
  msgLen=GWEN_Msg_GetBytesInBuffer(msg);

  if (msgLen>1) {
    const uint8_t *payloadPtr;
    uint32_t payloadLen;

    payloadLen=GWEN_Msg_GetParsedPayloadSize(msg);
    payloadPtr=msgPtr+GWEN_Msg_GetParsedPayloadOffset(msg);
    if (payloadPtr && payloadLen>=2)
      return (payloadPtr[0]<<8)+payloadPtr[1];
  }
  return 0;
}



void AQH_PubResponseMqttMsg_DumpToBuffer(const GWEN_MSG *msg, GWEN_BUFFER *dbuf, const char *sText)
{
  uint8_t msgType;
  uint16_t packetId;

  msgType=AQH_MqttMsg_GetMsgTypeAndFlags(msg);
  packetId=AQH_PubResponseMqttMsg_GetPacketId(msg);
  GWEN_Buffer_AppendArgs(dbuf, "%s %s (packet id: %04x)", AQH_MqttMsg_MsgTypeToString(msgType & 0xf0), sText, packetId);
}






