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

#include <gwenhywfar/debug.h>

#include <time.h>



AQH_MESSAGE *AQH_MqttEndpoint_WaitForConnAckMsg(AQH_OBJECT *mqttEndpoint, int timeoutInSeconds)
{
  return AQH_MqttEndpoint_WaitForMsg(mqttEndpoint, AQH_MQTTMSG_MSGTYPE_CONNACK, timeoutInSeconds);
}



AQH_MESSAGE *AQH_MqttEndpoint_WaitForMsg(AQH_OBJECT *mqttEndpoint, uint8_t t, int timeoutInSeconds)
{
  time_t startTime;

  startTime=time(NULL);
  t&=0xf0;

  for (;;) {
    AQH_MESSAGE_LIST *msgList;
    time_t now;

    msgList=AQH_Endpoint_GetMsgInList(mqttEndpoint);
    if (msgList) {
      AQH_MESSAGE *msg;

      msg=AQH_Message_List_First(msgList);
      while(msg) {
        uint8_t msgTypeAndFlags;

        msgTypeAndFlags=AQH_MqttMessage_GetTypeAndFlags(msg);
        if ((msgTypeAndFlags & 0xf0) == t) {
          AQH_Message_List_Del(msg);
          return msg;
        }
        msg=AQH_Message_List_Next(msg);
      }
    }

    now=time(NULL);
    if (now-startTime>timeoutInSeconds) {
      DBG_INFO(NULL, "Timeout");
      break;
    }

    AQH_EventLoop_Run(AQH_Object_GetEventLoop(mqttEndpoint), 500);
  } /* for */

  return NULL;
}







