//https://circuits4you.com/2019/01/11/nodemcu-esp8266-arduino-json-parsing-example/

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
#include <LiquidCrystal_I2C.h>

const char* SSID = "IFSC";
const char* PASSWORD = "campuschapeco";
LiquidCrystal_I2C lcd(0x27,16,2);
String BASE_URL = "https://projeto8.migueldebarba.com.br/alanc/testejson.php";

String payload;
String linhaum,linhadois;

void initSerial();
void initWiFi();
void httpRequest(String path);

// ############### OBJECTS ################# //

WiFiClient client;
HTTPClient http;
void setup() {
  initSerial();
  initWiFi();
  lcd.init();
  lcd.setBacklight(HIGH);
}

// ############# HTTP REQUEST ################ //

void httpRequest(String path)
{
  String payload = makeRequest(path);
  if (!payload) {
    return;
  }
}

String makeRequest(String path)
{
  http.begin(client, BASE_URL);
  int httpCode = http.GET();                                  //Send the request
    if (httpCode > 0) { //Check the returning code
      payload = http.getString();   //Get the request response payload
    }

  if (httpCode < 0) {
    Serial.println("request error - " + httpCode);
    return "";
  }
  if (httpCode != HTTP_CODE_OK) {
    return "";
  }
  String response =  http.getString();
  http.end();
  return response;
}

// implementacao dos prototypes

void initSerial() {
  Serial.begin(115200);
}

void initWiFi() {
  delay(10);
  Serial.println("Conectando-se em: " + String(SSID));

  WiFi.begin(SSID, PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.print("Conectado na Rede " + String(SSID) + " | IP => ");
  Serial.println(WiFi.localIP());
  lcd.setCursor(0,0);
  lcd.print(SSID);
  lcd.setCursor(0,1);
  lcd.print(WiFi.localIP());
  delay(2000);
 
}

void showLetters(int printStart, int startLetter)
{
  lcd.setCursor(printStart,0);
  for (int currentLetter = startLetter; currentLetter < linhaum.length(); currentLetter++)
  {
    lcd.print(linhaum[currentLetter]);
  } 
  lcd.print(" ");
  
  lcd.setCursor(printStart,1);
  for (int currentLetter = startLetter; currentLetter < linhadois.length(); currentLetter++)
  {
    lcd.print(linhadois[currentLetter]);
  } 

  lcd.print(" ");
  delay(250); 
  
}

void loop() {
  Serial.println("[GET] /testejson.php");
  Serial.println("");
  httpRequest("GET");
  Serial.println("payload:  " + payload);

  // Cria documento JSON (buffer)
  StaticJsonDocument<300> doc;
  // Desserializa
  DeserializationError error = deserializeJson(doc, payload);

  if (error) {
    Serial.print(F("Erro ao desserializar: "));
    Serial.println(error.f_str());
    return;
  }  

  // Como Ã© um array, pegamos o primeiro elemento
  JsonObject painel = doc[0];

  // Acessa os campos
  int idpainel = painel["idpainel"];
  const char* mac = painel["mac_idmac"];
  const char* nome = painel["nome"];
  int ledr = painel["ledr"];
  int ledg = painel["ledg"];
  int ledb = painel["ledb"];
  
  linhaum = painel["linhaum"].as<String>();  
  linhadois = painel["linhadois"].as<String>();  
  int t1=linhaum.length();
  int t2=linhadois.length();

  // Mostra no Display
  for (int letter = 1; letter <= t1; letter++)  //scroll off to left
  {    showLetters(0, letter);  }
  
  // Mostra no Serial
  Serial.println("=== Dados do Painel ===");
  Serial.print("ID: "); Serial.println(idpainel);
  Serial.print("MAC: ");  Serial.println(mac);
  Serial.print("Nome: ");  Serial.println(nome);
  Serial.print("LED R: ");  Serial.println(ledr);
  Serial.print("LED G: ");  Serial.println(ledg);
  Serial.print("LED B: ");  Serial.println(ledb);  
  Serial.print("Linha UM: ");  Serial.println(linhaum);  
  Serial.print("Linha DOIS: ");  Serial.println(linhadois);  
  delay(5000);
}