/*
  ESP32 HTTPClient Accuweather API Example

  hhttps://wokwi.com/projects/349473174878945874

  Copyright (C) 2022, Trang Bee
*/

#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 = "";

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

const String urlTemperature1day = "http://dataservice.accuweather.com/forecasts/v1/daily/1day/353412?apikey=zyQNUcoB4ZbyPQLWFfeRzMohOIrw4Cxc&language=en-us&metric=true";
const String urlTemperature5day = "http://dataservice.accuweather.com/forecasts/v1/daily/1day/353412?apikey=zyQNUcoB4ZbyPQLWFfeRzMohOIrw4Cxc&language=vi-vn&metric=true";

String getWeather1day() {
  HTTPClient http;
  http.useHTTP10(true);
  http.begin(urlTemperature1day);
  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 "<error>";
  }

  Serial.println(doc.as<String>());
  String generalInfo = doc["Headline"]["Text"].as<String>();
  String joke = doc["joke"].as<String>();
  String setup = doc["setup"].as<String>();
  String delivery = doc["delivery"].as<String>();
  http.end();
  //return type.equals("single") ? joke : setup + "  " + delivery;
  return generalInfo;
}

void nextJoke() {
  tft.setTextColor(ILI9341_WHITE);
  tft.println("\nDang lay thong tin thoi tiet...");

  String generalInfo = getWeather1day();
  tft.setTextColor(ILI9341_GREEN);
  tft.println(generalInfo);
}

void setup() {
  pinMode(BTN_PIN, INPUT_PULLUP);

  WiFi.begin(ssid, password, 6);

  tft.begin();
  tft.setRotation(1);

  tft.setTextColor(ILI9341_WHITE);
  tft.setTextSize(2);
  tft.print("Ket noi den WiFi Router");

  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    tft.print(".");
  }

  tft.print("\nKET NOI THANH CONG! IP=");
  tft.println(WiFi.localIP());

  nextJoke();
}

void loop() {
  if (digitalRead(BTN_PIN) == LOW) {
    tft.fillScreen(ILI9341_BLACK);
    tft.setCursor(0, 0);
    nextJoke();
  }

  delay(100);
}