#ifndef HOMEKIT_LIB_MQTT_H
#define HOMEKIT_LIB_MQTT_H

#include <vector>
#include <map>
#include <cstdint>
#include <espMqttClient.h>
#include <Ticker.h>
#include "./module.h"

namespace homekit::mqtt {
    
extern const uint8_t MQTT_CA_FINGERPRINT[];
extern const char MQTT_SERVER[];
extern const uint16_t MQTT_PORT;
extern const char MQTT_USERNAME[];
extern const char MQTT_PASSWORD[];
extern const char MQTT_CLIENT_ID[];
extern const char MQTT_SECRET[CONFIG_NODE_SECRET_SIZE+1];

class MqttModule;

class Mqtt {
private:
    String nodeId;
    WiFiClientSecure httpsSecureClient;
    espMqttClientSecure client;
    Ticker reconnectTimer;
    std::vector<MqttModule*> modules;
    std::map<String, MqttModule*> moduleSubscriptions;
    bool connected;

    uint16_t subscribe(const String& topic, uint8_t qos = 0);

public:
    Mqtt();
    void connect();
    void disconnect();
    void reconnect();
    void loop();
    void addModule(MqttModule* module);
    void subscribeModule(String& topic, MqttModule* module, uint8_t qos = 0);
    uint16_t publish(const String& topic, uint8_t* payload, size_t length);
};

}

#endif //HOMEKIT_LIB_MQTT_H
