#include "settings.h"


Settings::preferences_t Settings::Settings::prefs;


// Singleton instance
Settings& Settings::getInstance() {
    static Settings instance;
    return instance;
}

// Constructor
Settings::Settings() {
    loadSettings(); // Load dataset from persistent storage
    // Initialize default values for the dataset
}

// Destructor
Settings::~Settings() {
}

// Save the current dataset to persistent storage
void Settings::saveSettings() {
    preferences.begin("settings", false); // Open preferences in read-write mode
    preferences.putFloat("deftemp", prefs.defTemp);
    preferences.putBool("enBuff", prefs.enBuff);
    glblData.enBuff = prefs.enBuff;
    preferences.putString("hostname", prefs.hostname);
    preferences.putString("mqtt_server", prefs.mqtt_server);
    preferences.putString("mqtt_topic", prefs.mqtt_topic);
    preferences.putString("ntpServer", prefs.ntpServer);
    preferences.putInt("mqtt_port", prefs.mqtt_port);
    preferences.putBool("relPowerSave", glblData.relPowerSave);
    preferences.end();
}

// Load the dataset from persistent storage
void Settings::loadSettings() {
    preferences.begin("settings", true); // Open preferences in read mode
    prefs.defTemp = preferences.getFloat("deftemp", 22.0f);
    glblData.settemp = prefs.defTemp;
    prefs.enBuff = preferences.getBool("enBuff", false);
    glblData.enBuff = prefs.enBuff;
    uint32_t mac = (uint32_t) ESP.getEfuseMac();
    char tmp[20];
    sprintf(tmp, "TMP-%08x", mac);
    strncpy(prefs.hostname, preferences.getString("hostname", tmp).c_str(), sizeof(prefs.hostname) - 1);
    prefs.hostname[sizeof(prefs.hostname) - 1] = '\0'; // Ensure null-termination
    strncpy(prefs.mqtt_server, preferences.getString("mqtt_server", "nas.local").c_str(), sizeof(prefs.mqtt_server) - 1);
    prefs.mqtt_server[sizeof(prefs.mqtt_server) - 1] = '\0'; // Ensure null-termination
    strncpy(prefs.mqtt_topic, preferences.getString("mqtt_topic", "Raumtemp/EG/Unkonfiguriert").c_str(), sizeof(prefs.mqtt_topic) - 1);
    prefs.mqtt_topic[sizeof(prefs.mqtt_topic) - 1] = '\0'; // Ensure null-termination
    strncpy(prefs.ntpServer, preferences.getString("ntpServer", "nas.local").c_str(), sizeof(prefs.ntpServer) - 1);
    prefs.ntpServer[sizeof(prefs.ntpServer) - 1] = '\0'; // Ensure null-termination
    prefs.mqtt_port = preferences.getInt("mqtt_port", 1883);
    glblData.relPowerSave = preferences.getBool("relPowerSave", true);
    preferences.end();
}

Settings::preferences_t& Settings::getPrefs(void) {
    return prefs;
}