/*
 * Stairs
 * Copyright 2017 (c) Mark van Renswoude
 *
 * https://git.x2software.net/pub/Stairs
*/
#include "./abstractjson.h"
#include <FS.h>


void AbstractJsonSettings::read()
{
  _d(getDebugPrefix()); _dln(" :: opening file");
  File settingsFile = SPIFFS.open(getFilename(), "r");
  if (!settingsFile)
  {
    _d(getDebugPrefix()); _dln(" :: failed to open file");
    return;
  }

  size_t size = settingsFile.size();
  if (size > 1024)
  {
    _d(getDebugPrefix()); _dln(" :: file size is too large");
    return;
  }

  if (size == 0)
  {
    _d(getDebugPrefix()); _dln(" :: zero size file");
    return;
  }

  std::unique_ptr<char[]> buf(new char[size]);
  settingsFile.readBytes(buf.get(), size);
  settingsFile.close();

  _dln(buf.get());

  if (fromJson(buf.get()))
  {
    _d(getDebugPrefix());
    _dln(" :: read from file");
  }
  else
  {
    _d(getDebugPrefix());
    _dln(" :: failed to parse file");
  }
}


void AbstractJsonSettings::write()
{
  _d(getDebugPrefix()); _dln(" :: opening file for writing");
  File settingsFile = SPIFFS.open(getFilename(), "w");
  if (!settingsFile)
  {
    _d(getDebugPrefix()); _dln(" :: failed to open file for writing");
    return;
  }

  toJson(settingsFile);
  settingsFile.close();
  _d(getDebugPrefix()); _dln(" :: written to file");
}


bool AbstractJsonSettings::fromJson(char* data)
{
  return fromJson(data, nullptr);
}
