#include "mgos.h"
#include "mgos_mqtt.h"

uint32_t mqtt_pub_count=0;
uint32_t mqtt_sub_count=0;

static sub_handler_t s_handler;
static void *s_handler_ud;

static mg_event_handler_t s_global_handler;
static void *s_global_handler_ud;

void mgos_mqtt_pub(char *t, char *m, int m_len, int flags, bool persist) {
  LOG(LL_INFO, ("Sending topic='%s' msg='%s' persist=%s", t, m, persist?"ON":"OFF"));
  mqtt_pub_count++;
}

void mgos_mqtt_sub(char *t, sub_handler_t cb, void *ud) {
  LOG(LL_INFO, ("Subscribing to topic='%s'", t));
  s_handler = cb;
  s_handler_ud = ud;
}

void mgos_mqtt_inject(char *topic, char *msg) {
  LOG(LL_INFO, ("Injecting topic='%s' msg='%s'", topic, msg));
  mqtt_sub_count++;
  if (s_handler)
    s_handler(NULL, topic, strlen(topic), msg, strlen(msg), s_handler_ud);
}

void mgos_mqtt_add_global_handler(mqtt_event_handler_t handler, void *ud) {
  s_global_handler = handler;
  s_global_handler_ud = ud;
}