#include "mqtt_ota.h"

#include "esp_log.h"
#include "esp_system.h"
#include "esp_ota_ops.h"

#include <qthing.h>

#define TAG "MQTT_OTA"


esp_ota_handle_t ota_handle = 0;
const esp_partition_t* partition = NULL;

void handle_ota_message(const multipart_message_t& message) {
    ESP_LOGI(TAG, "length=%d offset=%d", message.length, message.offset);

    esp_err_t err;

    if (message.offset == 0) {  // first ota message
        partition = esp_ota_get_next_update_partition(NULL);
        err = esp_ota_begin(partition, message.total_length, &ota_handle);
        if (err != ESP_OK) ESP_LOGW(TAG, "BEGIN OTA FAILED!");
    }

    err = esp_ota_write(ota_handle, (const void*) message.payload, message.length);
    if (err != ESP_OK) ESP_LOGW(TAG, "WRITE OTA FAILED!");

    if (message.offset + message.length == message.total_length) {  // last ota message
        err = esp_ota_end(ota_handle);
        if (err != ESP_OK) ESP_LOGW(TAG, "END OTA FAILED!");
        err = esp_ota_set_boot_partition(partition);
        if (err != ESP_OK) ESP_LOGW(TAG, "FINALIZE OTA FAILED!");
        esp_restart();
    }

}