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


void MotionTriggerSettings::toJson(Print &print)
{
  DynamicJsonBuffer jsonBuffer(JSON_ARRAY_SIZE(2) + 2*JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(5));

  JsonObject& root = jsonBuffer.createObject();
  root["enabled"] = enabled();
  root["enabledDuringTimeTrigger"] = (uint8_t)enabledDuringTimeTrigger();
  root["enabledDuringDay"] = enabledDuringDay();
  root["transitionTime"] = transitionTime();
  root["delay"] = delay();

  JsonArray& jsonTriggers = root.createNestedArray("triggers");

  for (uint8_t i = 0; i < triggerCount(); i++)
  {
    MotionTrigger* triggerItem = trigger(i);

    JsonObject& jsonTrigger = jsonTriggers.createNestedObject();
    jsonTrigger["pin"] = triggerItem->pin;
    jsonTrigger["brightness"] = triggerItem->brightness;
    jsonTrigger["direction"] = (uint8_t)triggerItem->direction;
    jsonTrigger["enabled"] = triggerItem->enabled;
  }

  root.printTo(print);
}


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

  DynamicJsonBuffer jsonBuffer(JSON_ARRAY_SIZE(2) + 2*JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(5) + 200);
  JsonObject& root = jsonBuffer.parseObject(data);

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


  enabled(root["enabled"]);

  JsonVariant jsonEnabledDuringTimeTrigger = root["enabledDuringTimeTrigger"];
  if (jsonEnabledDuringTimeTrigger.success())
  {
    if (jsonEnabledDuringTimeTrigger.is<bool>())
    {
      // Backwards compatibility
      if (jsonEnabledDuringTimeTrigger.as<bool>())
        enabledDuringTimeTrigger(MotionDuringTimeTrigger::Always);
      else
        enabledDuringTimeTrigger(MotionDuringTimeTrigger::Never);

    }
    else
    {
      enabledDuringTimeTrigger((MotionDuringTimeTrigger)jsonEnabledDuringTimeTrigger.as<uint8_t>());
    }
  }
  else
    enabledDuringTimeTrigger(MotionDuringTimeTrigger::Never);

  transitionTime(root["transitionTime"]);
  delay(root["delay"]);

  if (root.containsKey("triggers"))
  {
    JsonArray& jsonTriggers = root["triggers"];
    if (mTriggers != nullptr)
      delete [] mTriggers;

    mTriggerCount = jsonTriggers.size();
    mTriggers = new MotionTrigger[mTriggerCount];


    for (uint8_t i = 0; i < mTriggerCount; i++)
    {
      JsonObject& jsonTrigger = jsonTriggers[i];
      MotionTrigger* trigger = &mTriggers[i];

      trigger->pin = jsonTrigger["pin"];
      trigger->brightness = jsonTrigger["brightness"];
      trigger->direction = (MotionDirection)(uint8_t)jsonTrigger["direction"];
      trigger->enabled = jsonTrigger["enabled"];
    }
  }

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

  return true;
}
