#include "./diagnostics.h"
#include <homekit/wifi.h>
#include <ESP8266WiFi.h>

namespace homekit::mqtt {

static const char TOPIC_DIAGNOSTICS[] = "diag";
static const char TOPIC_INITIAL_DIAGNOSTICS[] = "d1ag";

void MqttDiagnosticsModule::init(Mqtt& mqtt) {}

void MqttDiagnosticsModule::tick(Mqtt& mqtt) {
    if (!tickElapsed())
        return;

    auto cfg = config::read();

    if (!initialSent) {
        MqttInitialDiagnosticsPayload stat{
                .ip = wifi::getIPAsInteger(),
                .fw_version = CONFIG_FW_VERSION,
                .rssi = wifi::getRSSI(),
                .free_heap = ESP.getFreeHeap(),
                .flags = DiagnosticsFlags{
                        .state = 1,
                        .config_changed_value_present = 1,
                        .config_changed = static_cast<uint8_t>(cfg.flags.node_configured ||
                                                               cfg.flags.wifi_configured ? 1 : 0)
                }
        };
        mqtt.publish(TOPIC_INITIAL_DIAGNOSTICS, reinterpret_cast<uint8_t*>(&stat), sizeof(stat));
        initialSent = true;
    } else {
        MqttDiagnosticsPayload stat{
                .rssi = wifi::getRSSI(),
                .free_heap = ESP.getFreeHeap(),
                .flags = DiagnosticsFlags{
                        .state = 1,
                        .config_changed_value_present = 0,
                        .config_changed = 0
                }
        };
        mqtt.publish(TOPIC_DIAGNOSTICS, reinterpret_cast<uint8_t*>(&stat), sizeof(stat));
    }
}

}
