#include "config.h"
#include "LittleFS.h"

void initialize_config(Config *config, JsonDocument json) {
    config->ssid = strdup(json["ssid"]);
    config->psk = strdup(json["psk"]);
    config->mqtt_host = strdup(json["mqtt_host"]);
    config->mqtt_user = strdup(json["mqtt_user"]);
    config->mqtt_password = strdup(json["mqtt_password"]);
    config->topic = strdup(json["mqtt_topic"]);
    config->device_id = strdup(json["device_id"]);
    config->mqtt_port = json["mqtt_port"];
    config->sleep_time = minutes_to_milliseconds(json["sleep_time"]);
}

bool load_config_file(const char *file_path, Config *config) {
    if (!LittleFS.begin())
        return false;
    File config_file = LittleFS.open(file_path, "r");
    if (!config_file)
        return false;
    JsonDocument json;
    DeserializationError err = deserializeJson(json, config_file);
    if (err)
        return false;
    initialize_config(config, json);
    return true;
}

long minutes_to_milliseconds(int minutes) { return (minutes * 6e4); }
