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


StepsSettings::StepsSettings()
{
  for (uint8_t i = 0; i < MaxStepCount; i++)
  {
    mRange[i].start = 0;
    mRange[i].end = 4095;
  }
}


void StepsSettings::toJson(Print &print)
{
  DynamicJsonBuffer jsonBuffer(JSON_ARRAY_SIZE(16) + JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(2));

  JsonObject& root = jsonBuffer.createObject();
  root["count"] = count();
  root["useCurve"] = useCurve();

  JsonArray& jsonRanges = root.createNestedArray("ranges");
  for (uint8_t step = 0; step < MaxStepCount; step++)
  {
    JsonObject& jsonRange = jsonBuffer.createObject();
    jsonRange["start"] = rangeStart(step);
    jsonRange["end"] = rangeEnd(step);
    jsonRanges.add(jsonRange);
  }

  root.printTo(print);
}


bool StepsSettings::fromJson(char* data, bool* changed)
{
  if (changed != nullptr)
    *changed = false;

  DynamicJsonBuffer jsonBuffer(JSON_ARRAY_SIZE(16) + JSON_OBJECT_SIZE(3) + 80);
  JsonObject& root = jsonBuffer.parseObject(data);

  if (!root.success())
    return false;

  uint8_t jsonCount = root["count"];
  bool jsonUseCurve = root["useCurve"];

  if (jsonCount != count() ||
      jsonUseCurve != useCurve())
  {
    count(jsonCount);
    useCurve(jsonUseCurve);

    if (changed != nullptr)
      *changed = true;
  }


  JsonArray& jsonRanges = root["ranges"];
  uint8_t stepCount = jsonRanges.size();
  if (stepCount >= MaxStepCount)
    stepCount = MaxStepCount - 1;

  for (uint8_t step = 0; step < stepCount; step++)
  {
    JsonObject& jsonRange = jsonRanges[step];

    uint16_t start = jsonRange["start"];
    uint16_t end = jsonRange["end"];

    if (start != rangeStart(step) || end != rangeEnd(step))
    {
      rangeStart(step, start);
      rangeEnd(step, end);

      if (changed != nullptr)
        *changed = true;
    }
  }

  return true;
}