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

static const char *TAG = "MQTT";

// Why are we not zeroing this? 
static const esp_mqtt_client_config_t mqtt_cfg = {
    .host = "esp1.leigh-co.com",
    .port = 52019,
    .client_id = "XP001|securemode=3,signmethod=hmacsha1|",
    .username = NULL,
    .password = NULL
};

static esp_err_t mqttF_event_handler(esp_mqtt_event_handle_t event)
{
    esp_mqtt_client_handle_t client = event->client;

    int msg_id;
    switch (event->event_id) {
        case MQTT_EVENT_CONNECTED:
             msg_id = esp_mqtt_client_subscribe(client, "/sys/a1Swb0u95bV/XP001/thing/service/property/set", 0);//Subscribe topic
             ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
            break;
        case MQTT_EVENT_DISCONNECTED:
           //...
            break;
        case MQTT_EVENT_SUBSCRIBED:
           	//...
            break;
        case MQTT_EVENT_UNSUBSCRIBED:
           //...
            break;
        case MQTT_EVENT_PUBLISHED:
           	//...
            break;
        case MQTT_EVENT_DATA:
            ESP_LOGI(TAG, "MQTT_EVENT_DATA");
            printf("TOPIC=%.*s\r\n", event->topic_len, event->topic);
            printf("DATA=%.*s\r\n", event->data_len, event->data);

            cJSON *root = cJSON_Parse(event->data);
            if (!root) {
                printf("JSON format error:%s/r\n", cJSON_GetErrorPtr());
            } else {
             // DO SOME THINGS
            }     
            break;
        case MQTT_EVENT_ERROR:
           	//..
            break;
        default:
           //...
            break;
    }
    return ESP_OK;
}

void mqttFsend(esp_mqtt_client_handle_t *client)
{
    char topic[128];
    sprintf(topic, "LC.TELEMETRY");
   while(1)
    {
        esp_mqtt_client_publish(client, topic,  "{\"symbols\":[{\"name\":\"lc.test\",\"value\":\"1234\"}]}", 0, 1, 0);
        vTaskDelay(pdMS_TO_TICKS(1000)); // wait 5 seconds
    }
}

void mqttFexample() {
    esp_mqtt_client_handle_t *client = esp_mqtt_client_init(&mqtt_cfg);
    esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqttF_event_handler, client);
    mqttFsend(client);
}