/**
 *   ESP32 SvelteKit
 *
 *   A simple, secure and extensible framework for IoT projects for ESP32 platforms
 *   with responsive Sveltekit front-end built with TailwindCSS and DaisyUI.
 *   https://github.com/theelims/ESP32-sveltekit
 *
 *   Copyright (C) 2018 - 2023 rjwats
 *   Copyright (C) 2023 theelims
 *
 *   All Rights Reserved. This software may be modified and distributed under
 *   the terms of the LGPL v3 license. See the LICENSE file for details.
 **/

#include <SettingValue.h>

namespace SettingValue {
const String PLATFORM = "esp32";

/**
 * Returns a new string after replacing each instance of the pattern with a value generated by calling the provided
 * callback.
 */
String replaceEach(String value, String pattern, String (*generateReplacement)()) {
    while (true) {
        int index = value.indexOf(pattern);
        if (index == -1) {
            break;
        }
        value = value.substring(0, index) + generateReplacement() + value.substring(index + pattern.length());
    }
    return value;
}

/**
 * Generates a random number, encoded as a hex string.
 */
String getRandom() { return String(random(2147483647), HEX); }

/**
 * Uses the station's MAC address to create a unique id for each device.
 */
String getUniqueId() {
    uint8_t mac[6];
    esp_read_mac(mac, ESP_MAC_WIFI_STA);
    char macStr[13] = {0};
    sprintf(macStr, "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
    return String(macStr);
}

String format(String value) {
    value = replaceEach(value, "#{random}", getRandom);
    value.replace("#{unique_id}", getUniqueId());
    value.replace("#{platform}", PLATFORM);
    return value;
}

}; // end namespace SettingValue
