#include <ArduinoJson.h>
#include <detaBaseArduinoESP32.h>
#include <WiFiClientSecure.h>

char* apiKey = "b0eoyx13_Dgz6QtkNvHAUbcKu2BH2gNro8xbszang ";
char* detaID = "b0eoyx13";
char* detaBaseName = "MY_BASE";
const char * ssid = "Wokwi-GUEST"; //MENO WiFi SIETE
WiFiClientSecure client;
DetaBaseObject detaObj(client, detaID, detaBaseName, apiKey, true);
StaticJsonDocument<50> outer;

String jsonString;

int val = 1;

void setup() {
  Serial.begin(115200);
  StaticJsonDocument<20> internal;
  Serial.println("Let's begin initialization");
  JsonArray items = outer.createNestedArray("items");
  internal["modulo"] = val;
  items.add(internal);
  serializeJson(outer, jsonString);
  Serial.println(jsonString);
  Serial.println("Reached before WiFi init");
  WiFi.begin(ssid); //pripoj sa na wifi siet s heslom
  Serial.println("Waiting to connect to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  jsonString = "";

}

void loop() {
  StaticJsonDocument<120> receiving;
  outer["items"][0]["teste"] = val * 2;
  serializeJson(outer, jsonString);
  Serial.println(jsonString);

  result myResult = detaObj.putObject(jsonString.c_str());
  Serial.println();
  Serial.println(myResult.statusCode);
  Serial.println(myResult.reply);
  deserializeJson(receiving, myResult.reply);
  const char* assignedKey = receiving["processed"]["items"][0]["key"];
  val = receiving["processed"]["items"][0]["teste"];

  Serial.print("Key assigned by Deta:\t");
  Serial.println(assignedKey);
  Serial.print("Value received:\t");
  Serial.println(val);

  jsonString = "";
  delay(1000);
}