#include "configuration.h"
#include <SmingCore.h>

ClockConfig ActiveConfig;

ClockConfig loadConfig(void)
{
	DynamicJsonDocument doc(1024);
	ClockConfig cfg;
	if(Json::loadFromFile(doc, CLOCK_CONFIG_FILE)) {
		JsonObject network = doc["network"];
		cfg.NetworkSSID = network["ssid"].as<const char*>();
		cfg.NetworkPassword = network["password"].as<const char*>();

		JsonObject correction = doc["correction"];
		cfg.AddTZ = correction["TZ"];

		JsonObject light = doc["light"];
		cfg.LightTrhLow = light["low"];
		cfg.LightTrhHigh = light["high"];

		JsonObject bright = doc["bright"];
		cfg.BrightnessLow = bright["low"];
		cfg.BrightnessMiddle = bright["mid"];
		cfg.BrightnessHigh = bright["high"];
	} else {
		cfg.NetworkSSID = WIFI_SSID;
		cfg.NetworkPassword = WIFI_PWD;
	}
	return cfg;
}

void saveConfig(ClockConfig& cfg)
{
	ActiveConfig = cfg;

	DynamicJsonDocument doc(1024);
	auto network = doc.createNestedObject("network");
	network["ssid"] = cfg.NetworkSSID;
	network["password"] = cfg.NetworkPassword;

	auto correction = doc.createNestedObject("correction");
	correction["TZ"] = cfg.AddTZ;

	auto light = doc.createNestedObject("light");
  light["low"] = cfg.LightTrhLow;
  light["high"] = cfg.LightTrhHigh;

	auto bright = doc.createNestedObject("bright");
  bright["low"] = cfg.BrightnessLow;
  bright["mid"] = cfg.BrightnessMiddle;
  bright["high"] = cfg.BrightnessHigh;

	Json::saveToFile(doc, CLOCK_CONFIG_FILE, Json::Pretty);
}
