/****************************************************************************
 * 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/mqtt/m_mqtt_suback.h"
#include "aqhome/msg/mqtt/m_mqtt.h"

#include <gwenhywfar/text.h>
#include <gwenhywfar/debug.h>



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

AQH_MESSAGE *AQH_MqttMessageSubAck_new(uint8_t flags, uint16_t packetId, uint8_t result)
{
  AQH_MESSAGE *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=AQH_MqttMessage_new(AQH_MQTTMSG_MSGTYPE_SUBACK | flags,
                          GWEN_Buffer_GetUsedBytes(buf),
                          (const uint8_t*) GWEN_Buffer_GetStart(buf));
  GWEN_Buffer_free(buf);
  return msg;
}



int AQH_MqttMessageSubAck_GetPacketId(const AQH_MESSAGE *msg)
{
  int idx;

  idx=AQH_MqttMessage_GetOffsetOfPayload(msg);
  if (idx>0) {
    int len;

    len=(int)AQH_Message_GetUsedSize(msg)-idx;
    if (len>1) {
      if (AQH_MqttMessage_GetTypeAndFlags(msg) & (AQH_MQTTMSG_FLAGS_QOS2 | AQH_MQTTMSG_FLAGS_QOS1)) {
        uint8_t *ptr;

        ptr=AQH_Message_GetMsgPointer(msg);
        return (ptr[0]<<8)+ptr[1];
      }
    }
  }
  return 0;
}



int AQH_MqttMessageSubAck_GetResultCode(const AQH_MESSAGE *msg)
{
  int idx;

  idx=AQH_MqttMessage_GetOffsetOfPayload(msg);
  if (idx>0) {
    int len;

    if (AQH_MqttMessage_GetTypeAndFlags(msg) & (AQH_MQTTMSG_FLAGS_QOS2 | AQH_MQTTMSG_FLAGS_QOS1))
      idx+=2;
    len=(int)AQH_Message_GetUsedSize(msg)-idx;
    if (len>0) {
      uint8_t *ptr;

      ptr=AQH_Message_GetMsgPointer(msg);
      return *ptr;
    }
  }
  return GWEN_ERROR_BAD_DATA;
}



