/****************************************************************************
 * 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 "./loop_mqtt.h"
#include "./aqhomestorage_p.h"

#include "aqhome/mqtt/msg_mqtt_publish.h"

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




/* ------------------------------------------------------------------------------------------------
 * defines
 * ------------------------------------------------------------------------------------------------
 */

//#define I18N(msg) msg
#define I18S(msg) msg



/* ------------------------------------------------------------------------------------------------
 * forward declarations
 * ------------------------------------------------------------------------------------------------
 */

static void _handlePublishMsg(AQHOME_STORAGE *aqh, GWEN_MSG *msg);



/* ------------------------------------------------------------------------------------------------
 * implementations
 * ------------------------------------------------------------------------------------------------
 */



void AqHomeStorage_ReadAndHandleMqttMessages(AQHOME_STORAGE *aqh)
{
  GWEN_MSG *msg;

  while( (msg=GWEN_MsgEndpoint_TakeFirstReceivedMessage(aqh->mqttEndpoint)) ) {
    if ((AQH_MqttMsg_GetMsgTypeAndFlags(msg) & 0xf0)==(AQH_MQTTMSG_MSGTYPE_PUBLISH & 0xf0)) {
      _handlePublishMsg(aqh, msg);
    }
    else if ((AQH_MqttMsg_GetMsgTypeAndFlags(msg) & 0xf0)==(AQH_MQTTMSG_MSGTYPE_PINGRESP & 0xf0)) {
      DBG_INFO(AQH_LOGDOMAIN, "PING response received");
    }
    else {
      DBG_INFO(NULL, "Received unexpected MQTT message %02x", AQH_MqttMsg_GetMsgTypeAndFlags(msg));
    }
    GWEN_Msg_free(msg);
  }
}



int AqHomeStorage_MqttPing(AQHOME_STORAGE *aqh)
{
  GWEN_MSG *msgOut;

  DBG_INFO(AQH_LOGDOMAIN, "Sending PING");
  msgOut=GWEN_MqttMsg_new(AQH_MQTTMSG_MSGTYPE_PINGREQ, 0, NULL);
  if (msgOut==NULL) {
    DBG_ERROR(NULL, "Error creating message");
    return GWEN_ERROR_INTERNAL;
  }
  GWEN_MsgEndpoint_AddSendMessage(aqh->mqttEndpoint, msgOut);

  return 0;
}






void _handlePublishMsg(AQHOME_STORAGE *aqh, GWEN_MSG *msg)
{
  char *topic;
  char *value;
  
  topic=AQH_PublishMqttMsg_ExtractTopic(msg);
  value=AQH_PublishMqttMsg_ExtractValue(msg);
  
  if (topic && value)
    AQH_Storage_HandleMqttPublish(aqh->storage, topic, value);
  else {
    DBG_ERROR(NULL, "Either topic or value missing in PUBLISH msg");
  }
  free(value);
  free(topic);
}




