#pragma once

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//  MQTT Functions.
//	Both for Incoming and Outgoing MQTT Messages
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// Publishes a message on the MQTT server. Message passed as an argument.
void PublishMqtt(const char * data) {
		if (mqttClient.connected()){
    	String topicData = String("vesper/") + DEV_ID + "/data";
    	mqttClient.publish(topicData.c_str(), 0, true, data);
		} else {
			LOG_ERROR("MQTT Not Connected ! Message Failed.");
		}
}

// Subscribes to certain topics on the MQTT Server.
void SuscribeMqtt() {

	  String topic = String("vesper/") + DEV_ID + "/control";
    uint16_t topic_id = mqttClient.subscribe(topic.c_str(), 2);
    LOG_INFO("Subscribing to Command topic, QoS 2, packetId: %d", topic_id);

}

// Handles incoming MQTT messages on subscribed topics.
// Could move logic out of this into a dedicated function.
void OnMqttReceived(char * topic, char * payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {

	String inc_topic = String("vesper/") + DEV_ID + "/control";

	// Don't know what this is. Check it out later.
	//String payloadContent = String(payload).substring(0, len);

	if (String(topic) == inc_topic){
		JsonDocument command = payload2json(payload);
		handleCommand(command);
	}
}
