/*
 * LEIGH:plc
 * Copyright 2022 Alex Leigh
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <mqtt_client.h>
#include <cJSON.h>
#include <esp_log.h>

#include "esp.h"

static const char *TAG = "mqtt";
static esp_mqtt_client_handle_t espG_client;

static const esp_mqtt_client_config_t espG_cfg = {
    .broker.address.uri = "mqtt://esp1.leigh-co.com:52019"};

static void espF_event_handler(void *event_handler_arg,
                               esp_event_base_t event_base,
                               int32_t event_id,
                               void *event_data)
{
    ESP_LOGI(TAG, "Event handler fired.");
}

/**
 * @brief Send a MQTT message to ESP.
 *
 * Send a MQTT message to ESP18. Note that after sending the message, 
 * this function will delete both msg and tags, so the caller should not
 * do so. 
 */
void espFsend(const char *dst, cJSON *msg, cJSON *tags)
{
    char topic[128];
    sprintf(topic, dst);    
    
    
    cJSON *envelope = cJSON_CreateObject();
    cJSON_AddStringToObject(envelope, "type", "lc.esp.api18.envelope");
    cJSON_AddItemToObject(envelope, "parameters", tags);
    cJSON_AddItemToObject(envelope, "payload", msg);

    ESP_LOGI(TAG, "Sending message...");
    char *jtxt = cJSON_PrintUnformatted(envelope);
    esp_mqtt_client_publish(espG_client, topic, jtxt, 0, 1, 0);
    free(jtxt);

    cJSON_Delete(envelope);
}

/**
 * @brief Initialize ESP client
 *
 * Initialize the ESP client. This function should only be called once.
 */
void espFinit()
{
    espG_client = esp_mqtt_client_init(&espG_cfg);
    esp_mqtt_client_register_event(espG_client, ESP_EVENT_ANY_ID, espF_event_handler, espG_client);
    esp_mqtt_client_start(espG_client);
}