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



void ConnectionSettings::toJson(Print &print)
{
  DynamicJsonBuffer jsonBuffer(JSON_OBJECT_SIZE(9));

  JsonObject& root = jsonBuffer.createObject();
  root["hostname"] = hostname();
  root["accesspoint"] = flag(AccessPoint);
  root["station"] = flag(StationMode);
  root["ssid"] = ssid();
  root["password"] = password();
  root["dhcp"] = flag(DHCP);
  root["ip"] = ip() != 0 ? ip().toString() : "";
  root["subnetmask"] = subnetMask() != 0 ? subnetMask().toString() : "";
  root["gateway"] = gateway() != 0 ? gateway().toString() : "";

  root.printTo(print);
}


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

  DynamicJsonBuffer jsonBuffer(JSON_OBJECT_SIZE(9) + 250);
  JsonObject& root = jsonBuffer.parseObject(data);

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

  IPAddress jsonIP;
  IPAddress jsonSubnetMask;
  IPAddress jsonGateway;

  const char* jsonHostname = root["hostname"];
  bool jsonAccessPoint = root["accesspoint"];
  bool jsonStation = root["station"];
  const char* jsonSSID = root["ssid"];
  const char* jsonPassword = root["password"];
  bool jsonDHCP = root["dhcp"];
  const char* jsonIPText = root["ip"];
  const char* jsonSubnetMaskText = root["subnetmask"];
  const char* jsonGatewayText = root["gateway"];

  if (jsonIPText == nullptr || !jsonIP.fromString(jsonIPText)) jsonIP = emptyIP;
  if (jsonSubnetMaskText == nullptr || !jsonSubnetMask.fromString(jsonSubnetMaskText)) jsonSubnetMask = emptyIP;
  if (jsonGatewayText == nullptr || !jsonGateway.fromString(jsonGatewayText)) jsonGateway = emptyIP;


  if (!(jsonAccessPoint || jsonStation))
    jsonAccessPoint = true;

  if ((!sameStr(jsonHostname, hostname())) ||
      (jsonAccessPoint != flag(AccessPoint)) ||
      (jsonStation != flag(StationMode)) ||
      (!sameStr(jsonSSID, ssid())) ||
      (!sameStr(jsonPassword, password())) ||
      (jsonDHCP != flag(DHCP)) ||
      (jsonIP != ip()) ||
      (jsonSubnetMask != subnetMask()) ||
      (jsonGateway != gateway()))
  {
    hostname(jsonHostname);
    flag(AccessPoint, jsonAccessPoint);
    flag(StationMode, jsonStation);
    ssid(jsonSSID);
    password(jsonPassword);
    flag(DHCP, jsonDHCP);
    ip(jsonIP);
    subnetMask(jsonSubnetMask);
    gateway(jsonGateway);

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

  return true;
}