#define MQTT

#include "grafik.h"
// #include "handlebme280.h"
#include "main.h"
#include "weifi.h"
// #include "interpolation.h"
#include "mqtt.h"


JsonDocument doc;

//-----------------------------------------
// MQTT message arrives
void onmessage(char *tp, byte *msg, unsigned int length)
{
  String topic = String(tp);
  msg[length] = '\0';
  String message = String((char *)(msg));
  Serial.printf("Message arrived: %s %s\n", topic.c_str(), message.c_str());
  DeserializationError error = deserializeJson(doc, message);
  if (error) {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.c_str());
    return;
  }
  bool istemp = true;
  float val = 0.0;

  if (topic.startsWith("hm/status/Aussen_Temp:1/")) {
    struct tm timeinfo = gettheTime(1);
    if (topic.endsWith("TEMPERATURE")) {
      istemp = true;
    }
    if (topic.endsWith("HUMIDITY")) {
      istemp = false;
    }
    val = doc["val"];
    setAussenDataValues(val, istemp, timeinfo);
  } else if (topic ==  MQTT_TOPIC "set/parameter") {
    if(doc.containsKey("bmerate")) {
      setBMEreadtime(doc["bmerate"]);
//      showRate(doc["bmerate"]);
    }
    if(doc.containsKey("updaterate")) {
      setBMEreadtime(doc["updaterate"]);
//      showRate(doc["updaterate"]);
    }
    // if(doc.containsKey("tempoffset")) {
    //   tempOffset = (float)doc["tempoffset"];
    // }
    // if(doc.containsKey("humoffset")) {
    //   humOffset = (float)doc["humoffset"];
    // }
    // Serial.printf("tempoffset: %.1f,  humoffset: %.1f\n",tempOffset, humOffset);    
  } else if (topic == MQTT_TOPIC "set/messwerte") {
      // aktuelle Messwerte kommen rein
      if (doc.containsKey("temperature")) {
          bmedata.temp = doc["temperature"];
    }
      if (doc.containsKey("humidity")) {
          bmedata.hum = doc["humidity"];
      }
  } else if (topic ==  MQTT_TOPIC "get") {
      if(doc.containsKey("send")) {
        if(doc["send"] == "ip") {
          char ip[30];
          sprintf(ip, "{\"ip\":\"%s\"}", WiFi.localIP().toString().c_str());
          client.publish(MQTT_TOPIC "get/ip", ip);
        }
      }
  }
}


// Connect or reconnect to MQTT and subscribe
void reconnect(void)
{
  while (!client.connected())
  {
    Serial.print("Reconnecting...");
    bool erg = client.connect(CLIENT_ID, MQTT_USER, MQTT_PASSWD);
    Serial.println(erg);

    if (!client.connect(CLIENT_ID, MQTT_USER, MQTT_PASSWD))
    {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" retrying in 5 seconds");
      delay(5000);
    }
  }
  Serial.println("Connected");
  client.subscribe(MQTT_TOPIC "set/parameter");
  client.subscribe(MQTT_TOPIC "set/messwerte");
  client.subscribe(MQTT_TOPIC "get");
  client.subscribe("hm/status/Aussen_Temp:1/#");
}

void doPublish(float temp, float hum, float tm, float hm) {
    char payload[80];
    sprintf(payload, "{\"temperature\":%.1f,\"tempmess\":%.1f,\"humidity\":%.1f,\"hummess\":%.1f}", temp, tm, hum, hm);
    client.publish(MQTT_PUB_TEMP, payload);
    Serial.printf("Published: %s %s\n", MQTT_PUB_TEMP, payload);
}


// check MQTT in the loop
void checkMQTT(void) {
  if (!client.connected())
  {
    
    Serial.println("try to reconnect");
    reconnect();
  }
  client.loop();
}


// Setup MQTT client
void setup_mqtt(void) {
  Serial.printf("Setup MQTT to broker %s ...\n", MQTT_BROKER);
  client.setClient(espClient);
  client.setServer(MQTT_BROKER, MQTT_PORT);
  client.setCallback(onmessage);
}

