#include "wlan.h"

void initialize_wlan() { WiFi.onEvent(wlan_connection_handler); }

void initialize_mqtt() {
    mqtt_client.onDisconnect(on_mqtt_disconnection);
    mqtt_client.setServer(config->mqtt_host, config->mqtt_port);
    mqtt_client.setCredentials(config->mqtt_user, config->mqtt_password);
    Serial.println("MQTT initialization complete");
}

void connect_wlan() { WiFi.begin(config->ssid, config->psk); }

void connect_mqtt() {
    Serial.println("Connecting to MQTT");
    mqtt_client.connect();
}

void wlan_connection_handler(WiFiEvent_t event) {
    Serial.printf("[WiFi-event] event: %d\n", event);
    switch (event) {
    case SYSTEM_EVENT_STA_GOT_IP:
        Serial.println("WiFi connected");
        connect_mqtt();
        break;
    case SYSTEM_EVENT_STA_DISCONNECTED:
        Serial.println("WiFi disconnected");
        mqtt_connection_timer.detach();
        wlan_connection_timer.once(2, connect_wlan);
        break;
    }
}

void on_mqtt_disconnection(AsyncMqttClientDisconnectReason reason) {
    Serial.println("MQTT disconnected");

    if (WiFi.isConnected()) {
        mqtt_connection_timer.once(2, connect_mqtt);
    }
}

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

void mqtt_transfer(float *data) {
    char buffer[100];
    size_t payload_size = construct_json(data, buffer, 100);
    uint16_t response =
        mqtt_client.publish(config->topic, 2, true, buffer, payload_size);
    if (response)
        Serial.println("Data transferred successfully");
}
