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

#include <gwenhywfar/debug.h>



GWEN_MSG *GWEN_SubAckMqttMsg_new(uint8_t flags, uint16_t packetId, uint8_t result)
{
  GWEN_MSG *msg;
  GWEN_BUFFER *buf;

  buf=GWEN_Buffer_new(0, 64, 0, 1);
  if (flags & (AQH_MQTTMSG_FLAGS_QOS2 | AQH_MQTTMSG_FLAGS_QOS1)) {
    GWEN_Buffer_AppendByte(buf, (packetId>>8) & 0xff);
    GWEN_Buffer_AppendByte(buf, packetId & 0xff);
  }
  /* payload */
  GWEN_Buffer_AppendByte(buf, result);

  msg=GWEN_MqttMsg_new(AQH_MQTTMSG_MSGTYPE_SUBACK | flags, GWEN_Buffer_GetUsedBytes(buf), (const uint8_t*) GWEN_Buffer_GetStart(buf));
  GWEN_Buffer_free(buf);
  if (msg==NULL) {
    DBG_INFO(AQH_LOGDOMAIN, "here");
    return NULL;
  }
  return msg;
}



int AQH_SubAckMqttMsg_GetResultCode(const GWEN_MSG *msg)
{
  const uint8_t *msgPtr;
  uint32_t msgLen;

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

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

    flags=AQH_MqttMsg_GetMsgTypeAndFlags(msg);
    payloadLen=GWEN_Msg_GetParsedPayloadSize(msg);
    payloadPtr=msgPtr+GWEN_Msg_GetParsedPayloadOffset(msg);

    if (payloadLen>0) {
      if (flags & (AQH_MQTTMSG_FLAGS_QOS2 | AQH_MQTTMSG_FLAGS_QOS1)) {
        payloadLen--;
        payloadPtr++;
      }
      if (payloadLen>1)
        return (int) (payloadPtr[0]);
    }
  }

  return GWEN_ERROR_GENERIC;
}



void AQH_SubAckMqttMsg_DumpToBuffer(const GWEN_MSG *msg, GWEN_BUFFER *dbuf, const char *sText)
{
  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;

    GWEN_Buffer_AppendArgs(dbuf, "%s %s", AQH_MqttMsg_MsgTypeToString(msgPtr[0] & 0xf0), sText);
    payloadLen=GWEN_Msg_GetParsedPayloadSize(msg);
    payloadPtr=msgPtr+GWEN_Msg_GetParsedPayloadOffset(msg);
    if (payloadLen>=1)
      GWEN_Buffer_AppendArgs(dbuf, "(result=%d)", payloadPtr[0]);
  }
}






