/**
 * Utilities and helpers
 */

#ifndef CSPEMU_UTILS_H
#define CSPEMU_UTILS_H

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <string.h>
#include <nvs.h>
#include <common_utils/utils.h>

/** Error check macro for FreeRTOS status codes */
#define RTOS_ERROR_CHECK(code) if (pdPASS != (code)) ESP_ERROR_CHECK(ESP_FAIL);

/** Error check macro for NULL return value */
#define NULL_CHECK(code) if (NULL == (code)) ESP_ERROR_CHECK(ESP_FAIL);

/** Error check macro for CSP status codes */
#define CSP_ERROR_CHECK(code) if (CSP_ERR_NONE != (code)) ESP_ERROR_CHECK(ESP_FAIL);

/**
 * Reconnect to WiFi if there are saved credentials.
 * Called from the main event group handler.
 */
void try_reconn_if_have_wifi_creds(void);

/**
 * Helper to retrieve a bool value from the NVS. Internally uses 'u8'
 *
 * @param handle - NVS storage
 * @param key
 * @param out_value
 * @return success
 */
esp_err_t nvs_get_bool(nvs_handle handle, const char* key, bool* out_value);

/**
 * Helper to store a bool into the NVS. Internally uses 'u8'
 *
 * @param handle - NVS storage
 * @param key
 * @param value
 * @return success
 */
esp_err_t nvs_set_bool(nvs_handle handle, const char* key, bool value);

/**
 * Feed watchdogs (inside a busy wait loop)
 */
void feed_all_dogs(void);

/**
 * @brief     malloc() and snprintf() combined
 * @attention DO NOT use in if/for/do etc without braces.
 *
 * The caller is responsible for disposing of the allocated string afterwards.
 */
#define malloc_sprintf(var, n, format, ...) \
    char *var = calloc(n, 1); \
    if (!var) assert(0); \
    snprintf(var, n, format, ##__VA_ARGS__);

/**
 * Generate externs for an embedded file.
 * Variables {varname} and {varname}_end will be produced.
 */
#define efile(varname, filename) \
    extern const char varname[] asm("_binary_"filename"_start"); \
    extern const char varname##_end[] asm("_binary_"filename"_end");

/** Get embedded file size (must be declared with efile() first) */
#define efsize(varname) ((varname##_end) - (varname))

#endif //CSPEMU_UTILS_H