#include <Wire.h>
// #include <WiFi.h>
#include <ArduinoJson.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <HTTPClient.h> // Include the HTTPClient library

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

const char* ssid = "Wokwi-GUEST";
const char* password = "";
String APIKEY = "8c9f6eac52a56ea89b8c36162a6d60c7";
String CityID = "delhi"; 
WiFiClient client;
char servername[] = "iotml-1.onrender.com";
String result;
String city; 
String prediction; 

unsigned long channelID = 2235258; 
const char* writeAPIKey = "IU90PCW31HECJ1V5"; 

void setup() {
  Serial.begin(115200);
  
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  delay(200);
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.print("Connecting...");
  display.display();
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    display.print(".");
    display.display();
  }

  display.clearDisplay();
  display.setCursor(0, 0);
  display.println("Connected to WiFi");
  display.display();
  delay(1000);
  display.clearDisplay();
}

void loop() {
  if ((WiFi.status() == WL_CONNECTED)) { 
    
    HTTPClient http;
    while (1) { 
  
  
    http.begin("https://iotml-1.onrender.com/cityweather/jabalpur"); 
    int httpCode = http.GET();                                        
         Serial.print("inside loop ");
         Serial.println();
         Serial.print(httpCode);
         Serial.println();
        if(httpCode==200){
          String payload = http.getString();
          Serial.println(httpCode);
          Serial.println(payload);
        
       
        DynamicJsonDocument doc(1024);
        deserializeJson(doc, payload);
        
        
        city = doc["city"].as<const char*>();
        prediction = doc["prediction"].as<const char*>();
        break;
        }
      }
  
    // else {
    //   Serial.println("Error on HTTP request");
    // }
  
    http.end(); 
  }
  
  delay(10000);

  
  Serial.print("City: ");
  Serial.println(city);
  Serial.print("Prediction: ");
  Serial.println(prediction);

  
  display.clearDisplay();
  display.setCursor(0, 0);
  display.setTextColor(SSD1306_WHITE, SSD1306_BLACK);
  display.print("City: ");
  display.println(city);
 
  display.println();
  display.setTextColor(SSD1306_WHITE, SSD1306_BLACK);
  display.print("Prediction: ");
  display.println(prediction);

  display.display();
  
  delay(3000); 
}