#ifndef MQTTSENSORSOURCE_H
#define MQTTSENSORSOURCE_H

#include <QObject>
#include <QJsonObject>
#include <QtMqtt/QMqttClient>
#include <vector>

#include "sensor.h"
#include "mqttclient.h"

class MqttSensorSource : public QObject
{
	Q_OBJECT

	struct SensorSubscription
	{
		uint64_t id;
		QString topic;
		QString name;
		MqttClient::Subscription* subscription = nullptr;
	};

	std::vector<SensorSubscription> sensors;
	std::shared_ptr<MqttClient> client;

private:
	SensorSubscription& findSubscription(const QString& topic);

private slots:
	void onClientStateChanged(QMqttClient::ClientState state);
	void onMessageReceived(const QMqttMessage& message);

public slots:
	void onSensorAdded(Sensor sensor, Sensor::sensor_backend_type_t backend, QJsonObject payload);

public:
	explicit MqttSensorSource(QObject *parent = nullptr);
	~MqttSensorSource();
	void start(std::shared_ptr<MqttClient> client, const QJsonObject& settings);
	void addSensor(const QString& topic, const QString& name);
	void store(QJsonObject& json);

signals:
	void stateChanged(Sensor sensor, sensor_update_type_t type = SENSOR_UPDATE_BACKEND);
};

#endif // MQTTSENSORSOURCE_H
