/*
  ESP32 HTTPClient Jokes API Example

  https://wokwi.com/projects/342032431249883731

  Copyright (C) 2022, Uri Shaked
*/

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

const char* ssid = "Wokwi-GUEST";
const char* password = "";

uint8_t fontSize = 2;
#define BTN_PIN 5
#define TFT_DC 2
#define TFT_CS 15
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);

const String url = "https://altablogs.vercel.app/api/bmkg-now";

void display(String data, int delayInt = 100) {
  tft.fillScreen(ILI9341_BLACK);
  tft.setTextSize(fontSize + 4);
  tft.setTextColor(ILI9341_CYAN);
  tft.setCursor(0, 0);
  tft.println(data);
  delay(delayInt);
}

void setup() {
  Serial.begin(9600);
  pinMode(BTN_PIN, INPUT_PULLUP);

  WiFi.begin(ssid, password, 6);

  tft.begin();

  display("API TEST");
  while (WiFi.status() != WL_CONNECTED) {
    delay(10);
  }

  tft.fillScreen(ILI9341_BLACK);
  tft.setCursor(0, 0);

  // reload();
}

void loop() {
  HTTPClient http;
  http.useHTTP10(true);
  http.begin(url);
  http.GET();
  String result = http.getString();

  DynamicJsonDocument doc(2048);
  DeserializationError error = deserializeJson(doc, result);

  // Test if parsing succeeds.
  if (error) {
    Serial.print("deserializeJson() failed: ");
    Serial.println(error.c_str());
    return;
  }

  String WindDirection = doc["WindDirection"].as<String>();
  String humidity = doc["humidity"].as<String>();
  String temperature = doc["temperature"].as<String>();
  String weather = doc["weather"].as<String>();
  String time = doc["time"].as<String>();
  temperature.replace("°", "\xB0");
  http.end();

  display(time,3000);
  display(weather,1000);
  display(temperature,2000);
  display(weather,1000);
  display(time, 10);
}