/* 
   Código demonstrativo para a aula de Bancos de Dados aplicados à Internet das Coisas,
   Curso de Engenharia e Administração de Sistemas de Banco de Dados,
   Faculdade de Tecnologia - UNICAMP.

   https://arduinojson.org/v6/assistant/
   
*/

#include <WiFi.h>
#include <ArduinoHttpClient.h>
#include <ArduinoJson.h>

WiFiClient client;
HttpClient cliente = HttpClient(client,"dweet.io",80);

void setup() {

   Serial.begin(9600);
   while (!Serial)    {     }

   WiFi.begin("Wokwi-GUEST", "");   
   
   while(WiFi.status() != WL_CONNECTED) {
    delay(250);
  }

  Serial.println("-----------------------------------------------");
  Serial.print("Endereco IP: ");
  Serial.println(WiFi.localIP());
  Serial.println("-----------------------------------------------");
   
   delay(2000);
}

void loop() {
  
  Serial.println("Requisicao: GET");

  cliente.get("/get/latest/dweet/for/nome_dispositivo");
  Serial.println();
  
  int statusCode = cliente.responseStatusCode();
  String response = cliente.responseBody();

  Serial.print("Status: ");
  Serial.println(statusCode);
  Serial.print("Retorno: ");
  Serial.println(response);
  Serial.println("");

  StaticJsonDocument<512> doc;

  DeserializationError error = deserializeJson(doc, response);

  if (error) {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.f_str());
    return;
  }

  const char* this_ = doc["this"]; // "succeeded"
  const char* by_ = doc["by"]; // "getting"
  const char* the_ = doc["the"]; // "dweets"

  JsonObject with_0 = doc["with"][0];
  const char* with_0_thing = with_0["thing"]; // "nome_dispositivo"
  const char* with_0_created = with_0["created"]; // "2022-11-16T13:25:09.710Z"

  JsonObject with_0_content = with_0["content"];
  int with_0_content_A0 = with_0_content["A0"]; // 1000
  int with_0_content_A1 = with_0_content["A1"]; // 2000
  int with_0_content_A2 = with_0_content["A2"]; // 3000
  int with_0_content_A3 = with_0_content["A3"]; // 4000

  Serial.print("Dispositivo : ");
  Serial.println(with_0_thing);
  Serial.println("-----------------------------");
  Serial.print("A0 : ");
  Serial.println(with_0_content_A0);
  Serial.print("A1 : ");
  Serial.println(with_0_content_A1);
  Serial.print("A2 : ");
  Serial.println(with_0_content_A2);
  Serial.print("A3 : ");
  Serial.println(with_0_content_A3);
  Serial.println("");
  
  delay(15000);

}