#include "wlan.h"
#include "credentials.h"
#include <ArduinoJson.h>

void initial_connection() {
  WiFi.begin(SSID, PSK);
  WiFi.persistent(true);
  WiFi.setAutoConnect(true);
  WiFi.setAutoReconnect(true);
}

void connect_wlan(const int max_retries) {
  if (WiFi.SSID() != SSID)
    initial_connection();
  int retries = 0;
  while (WiFi.status() != WL_CONNECTED) {
    if (retries == max_retries)
      enter_deep_sleep(true);
    retries++;
    delay(1000);
    Serial.print(".");
  }
  Serial.println("WiFi connected");
}

void connect_mqtt(PubSubClient &client, const char *device_id,
                  const char *topic) {
  if (!client.connected())
    client.setServer(MQTT_HOST, MQTT_PORT);
  if (client.connect(device_id, MQTT_USER, MQTT_PASSWORD)) {
    Serial.println("MQTT connected");
    client.subscribe(topic);
  }
}

void disconnect_mqtt(PubSubClient &client, const char *topic) {
  Serial.println("Disconnecting MQTT");
  client.unsubscribe(topic);
  client.disconnect();
}

size_t construct_json(float *data, char *buffer, int buffer_size) {
  StaticJsonDocument<100> json;
  json["temperature"] = data[0];
  json["humidity"] = data[1];
  json["soil_humidity"] = data[2];
  size_t payload_size = serializeJson(json, buffer, buffer_size);
  return payload_size;
}

void mqtt_transfer(PubSubClient &client, const char *device_id,
                   const char *topic, float *data) {
  char buffer[100];
  connect_mqtt(client, device_id, topic);
  size_t payload_size = construct_json(data, buffer, 100);
  client.publish(topic, buffer, payload_size);
  Serial.println("Data transferred successfully");
}

void enter_deep_sleep(bool wifi_timeout) {
  Serial.println("Entering deep sleep");
  if (wifi_timeout)
    WiFi.disconnect();
  ESP.deepSleep(SLEEP_TIME, WAKE_RF_DEFAULT);
}
