#include "../include/configuration.h"

#include <SmingCore/SmingCore.h>

ClockConfig ActiveConfig;

ClockConfig
loadConfig ()
{
  DynamicJsonBuffer jsonBuffer;
  ClockConfig cfg;
  if (fileExist (CLOCK_CONFIG_FILE))
    {
      int size = fileGetSize (CLOCK_CONFIG_FILE);
      char* jsonString = new char[size + 1];
      fileGetContent (CLOCK_CONFIG_FILE, jsonString, size + 1);
      JsonObject& root = jsonBuffer.parseObject (jsonString);

      JsonObject& network = root["network"];
      cfg.NetworkSSID = String ((const char*) network["ssid"]);
      cfg.NetworkPassword = String ((const char*) network["password"]);

      JsonObject& correction = root["correction"];
      cfg.AddTZ = correction["TZ"];

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

      JsonObject& bright = root["bright"];
      cfg.BrightnessLow = bright["low"];
      cfg.BrightnessMiddle = bright["mid"];
      cfg.BrightnessHigh = bright["high"];

      delete[] jsonString;
    }
  else
    {
      cfg.NetworkSSID = WIFI_SSID;
      cfg.NetworkPassword = WIFI_PWD;
    }
  return cfg;
}

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

  DynamicJsonBuffer jsonBuffer;
  JsonObject& root = jsonBuffer.createObject ();

  JsonObject& network = jsonBuffer.createObject ();
  root["network"] = network;
  network["ssid"] = cfg.NetworkSSID.c_str ();
  network["password"] = cfg.NetworkPassword.c_str ();

  JsonObject& correction = jsonBuffer.createObject ();
  root["correction"] = correction;
  correction["TZ"] = cfg.AddTZ;

  JsonObject& light = jsonBuffer.createObject ();
  root["light"] = light;
  light["low"] = cfg.LightTrhLow;
  light["high"] = cfg.LightTrhHigh;

  JsonObject& bright = jsonBuffer.createObject ();
  root["bright"] = bright;
  bright["low"] = cfg.BrightnessLow;
  bright["mid"] = cfg.BrightnessMiddle;
  bright["high"] = cfg.BrightnessHigh;

  char buf[3048];
  root.prettyPrintTo (buf, sizeof(buf));
  fileSetContent (CLOCK_CONFIG_FILE, buf);
}

