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

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



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

AQH_MESSAGE *AQH_MqttMessageConnect_new(const char *protoName,
					uint8_t protoLevel,
					uint8_t connectFlags,
					uint16_t keepAliveTime,
					const char *clientId,
					const char *userName,
					const char *password)
{
  AQH_MESSAGE *msg;
  GWEN_BUFFER *buf;

  buf=GWEN_Buffer_new(0, 64, 0, 1);
  AQH_MqttMessage_AppendStringWithLenToBuffer(buf, protoName?protoName:"MQTT");
  GWEN_Buffer_AppendByte(buf, protoLevel?protoLevel:4);
  GWEN_Buffer_AppendByte(buf, connectFlags);
  GWEN_Buffer_AppendByte(buf, (keepAliveTime>>8) & 0xff);
  GWEN_Buffer_AppendByte(buf, keepAliveTime & 0xff);

  AQH_MqttMessage_AppendStringWithLenToBuffer(buf, clientId);
  /* here could be inserted: will topic, will message */
  if (connectFlags & AQH_MQTTMSG_CONNECT_FLAGS_USERNAME)
    AQH_MqttMessage_AppendStringWithLenToBuffer(buf, userName);
  if (connectFlags & AQH_MQTTMSG_CONNECT_FLAGS_PASSWD)
      AQH_MqttMessage_AppendStringWithLenToBuffer(buf, password);

  msg=AQH_MqttMessage_new(AQH_MQTTMSG_MSGTYPE_CONNECT, GWEN_Buffer_GetUsedBytes(buf), (const uint8_t*) GWEN_Buffer_GetStart(buf));
  GWEN_Buffer_free(buf);

  return msg;
}







