/* Hello World Example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/

/* ESP libraries */
#include "esp_log.h"
#include "esp_sleep.h"
#include "esp_system.h"

/* FreeRTOS */
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/task.h"

/* MISC */
#include "cbor.h"
#include "nvs_flash.h"

/* APP */
#include "app_bkp_ram.h"
#include "app_lvgl.h"
#include "app_mqtt.h"
#include "app_ui.h"
#include "app_wifi.h"
#include "app_weather.h"

#define APP_WAKE_INTERVAL_MS (30 * 60 * 1000)

#define APP_LOG_TAG "MAIN"

RTC_NOINIT_ATTR app_bkp_ram_t g_app_bkp;

void app_main(void) {
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());

        ret = nvs_flash_init();

        ESP_LOGW(APP_LOG_TAG, "NVS content corrupted or outdated, cleared.");
    }

    ESP_ERROR_CHECK(ret);

    if (app_wifi_init() != 0) {
        goto next_round;
    }

    if (app_mqtt_init() != 0) {
        goto next_round;
    }

    if (app_wifi_wait_ready(5000) != 0) {
        ESP_LOGW(APP_LOG_TAG, "Failed to connect to WiFi in time, bail out.");
        goto next_round;
    }

    if (app_lvgl_init() != 0) {
        goto next_round;
    }

    if (app_ui_init() != 0) {
        goto next_round;
    }

    if (app_weather_update() != 0) {
        goto next_round;
    }

    app_lvgl_start_flush();
    if (app_lvgl_wait_flush(5000) < 0) {
        ESP_LOGW(APP_LOG_TAG, "Did not get flush ready flag in time, bail out.");
        goto next_round;
    }

next_round:

    ESP_LOGI(APP_LOG_TAG, "Enter deep power down mode, interval: %d", APP_WAKE_INTERVAL_MS);
    app_lvgl_deinit();
    esp_deep_sleep(APP_WAKE_INTERVAL_MS * 1000);
}
