#include "ota_u.h"

void switch_to_ota(const char *target_label)
{
    // 通过标签获取分区
    const esp_partition_t *target_partition =
        esp_partition_find_first(ESP_PARTITION_TYPE_APP,
                                 ESP_PARTITION_SUBTYPE_ANY,
                                 target_label);
    if (!target_partition) {
        SYS_LOG_ERR("Partition '%s' not found!", target_label);
        return;
    }

    SYS_LOG_INF("Switching to %s at 0x%x", target_partition->label, target_partition->address);

    // 设置下次启动分区
    esp_err_t err = esp_ota_set_boot_partition(target_partition);
    if (err != ESP_OK) {
        SYS_LOG_ERR("Failed to set boot partition: %s", esp_err_to_name(err));
        return;
    }

    SYS_LOG_INF( "Switch successful, rebooting...");
    esp_restart();
}
// 获取ota信息
void get_partition_status(ota_u_t* otau)
{
    // 获取当前运行分区
    otau->running = esp_ota_get_running_partition();
    if (!otau->running) {
        SYS_LOG_ERR("Failed to get running partition");
        return;
    }
    //赋值ota分区
    if(strcmp(otau->running->label, OTA_TAG_0) == 0){
        otau->update = esp_partition_find_first(ESP_PARTITION_TYPE_APP,
                        ESP_PARTITION_SUBTYPE_ANY, OTA_TAG_1);
    }else{
        otau->update = esp_partition_find_first(ESP_PARTITION_TYPE_APP,
                        ESP_PARTITION_SUBTYPE_ANY, OTA_TAG_0);
    }
    SYS_LOG_INF("Running partition: %s at 0x%x", otau->running->label, otau->running->address);
}
void otau_init(ota_u_t* otau)
{
    
    if (esp_ota_begin(otau->update, OTA_SIZE_UNKNOWN, &otau->ota_handle) != ESP_OK) {
        SYS_LOG_ERR("esp_ota_begin failed!");
        return;
    }
    SYS_LOG_INF("Starting OTA update...");
}
uint8_t otau_write(ota_u_t* otau, void* data, uint32_t size)
{
    esp_err_t err = esp_ota_write(otau->ota_handle, data, size);
    if (err != ESP_OK) {
        SYS_LOG_ERR( "esp_ota_write failed! (%s)", esp_err_to_name(err));
        esp_ota_abort(otau->ota_handle);
        return 1;
    }
    otau->total_size += size;
    SYS_LOG_INF( "Received: %d bytes, Total: %d bytes", size, otau->total_size);
    return 0;
}
uint8_t otau_end(ota_u_t* otau)
{
    if (esp_ota_end(otau->ota_handle) != ESP_OK) {
        SYS_LOG_ERR("esp_ota_end failed!");
        return 1;
    }
    if (esp_ota_set_boot_partition(otau->update) != ESP_OK) {
        SYS_LOG_ERR("esp_ota_set_boot_partition failed!");
        return 1;
    }
    SYS_LOG_INF("OTA update successful! Rebooting...");
    return 0;
}