/*
   Código demonstrativo para a aula de Sistemas Embarcados,
   Curso de Ciência da Computação e Engenharia da Computação
   EEP.

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

*/

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

const String url = "http://things.ubidots.com/api/v1.6/data/raw/series";

HTTPClient cliente;

void setup() {

  Serial.begin(115200);
  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(1000);

}

void loop() {

  Serial.println("Requisicao: POST");

  // Substituir sua_variavel pelo id que identifica a variável desejada - ID.
  // String payload = "{\"variables\": [\"sua_variavel\",\"sua_variavel\",\"sua_variavel\",\"sua_variavel\"],\"columns\": [\"value.value\"], \"limit\": 1 }";

  String payload = "{\"variables\": [\"sua_variavel\",\"sua_variavel\",\"sua_variavel\",\"sua_variavel\"],\"columns\": [\"value.value\"], \"limit\": 1 }";

  int data = payload.length();

  cliente.begin(url);

  cliente.addHeader("Content-Type", "application/json");
  cliente.addHeader("Content-Length", String(data));

  // Substituir seu_token_default pela chave que identifica o seu token - TOKEN default.
  // cliente.addHeader("X-Auth-Token","seu_token_default");

  cliente.addHeader("X-Auth-Token","seu_token_default");

  int statusCode = cliente.POST(payload);
  String response = cliente.getString();

  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;
  }

  JsonArray results_0 = doc["results"][0];
  int results_0_0 = results_0[0];
  int results_0_1 = results_0[1];
  int results_0_2 = results_0[2];
  int results_0_3 = results_0[3];

  JsonArray columns = doc["columns"];
  const char* columns_0 = columns[0];
  const char* columns_1 = columns[1];
  const char* columns_2 = columns[2];
  const char* columns_3 = columns[3];

  Serial.print("Dispositivo : ");
  Serial.println("Objeto Virtual");
  Serial.println("-----------------------------");
  Serial.print("A0 : ");
  Serial.println(results_0_0);
  Serial.print("A1 : ");
  Serial.println(results_0_1);
  Serial.print("A2 : ");
  Serial.println(results_0_2);
  Serial.print("A3 : ");
  Serial.println(results_0_3);
  Serial.println("");

  delay(15000);

}