#include <Arduino.h>
#include <HardwareSerial.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>


class Weather {
    const char* tomorrowApiKey = "Enter API Key";
    String location;
    float temperature = 0.0;
    float humidity = 0.0;
    float windSpeed = 0.0;
    float precipitationProbability = 0.0;
    static const size_t JSON_BUFFER_SIZE = 8192; // 8KB
    boolean success = false;

    public:

      Weather() {
      }

      void setLocation(String city) {
        city.replace(" ", "%20");
        location = city;
      }

      float getTemperature() {
        return temperature;
      }

      float getHumidity() {
        return humidity;
      }

      float getWindSpeed() {
        return windSpeed;
      }

      float getPrec() {
        return precipitationProbability;
      }

      boolean checkSucess() {
        return success;
      }

      void fetchWeatherData() {
        if (WiFi.status() != WL_CONNECTED) {
          Serial.println("WiFi not connected");
          return;
        }

        WiFiClientSecure client;
        client.setInsecure();
        HTTPClient https;

        String url = String("https://api.tomorrow.io/v4/weather/realtime?location=") + 
                    location + "&apikey=" + tomorrowApiKey;

        Serial.println("Connecting to API...");
        https.begin(client, url);
        https.addHeader("accept", "application/json");

        int httpCode = https.GET();
        
        if (httpCode > 0) {
          Serial.printf("HTTP Response code: %d\n", httpCode);
          String payload = https.getString();
          
          // Create the JSON document
          DynamicJsonDocument doc(JSON_BUFFER_SIZE);
          
          // Clear the document before parsing
          doc.clear();
          
          // Parse the JSON
          DeserializationError error = deserializeJson(doc, payload);
          
          if (error) {
            Serial.print("deserializeJson() failed: ");
            Serial.println(error.c_str());
            Serial.println("Payload received:");
            Serial.println(payload);
          } else {
            // Successfully parsed JSON
            Serial.println("JSON parsed successfully!");
            
            // Navigate the JSON structure more carefully
            if (doc.containsKey("data")) {
              JsonObject data = doc["data"];
              if (data.containsKey("values")) {
                JsonObject values = data["values"];
                
                // Print each value if it exists
                if (values.containsKey("temperature")) {
                  Serial.print("Temperature: ");
                  Serial.println(values["temperature"].as<float>());
                  temperature = values["temperature"].as<float>();
                }
                
                if (values.containsKey("humidity")) {
                  Serial.print("Humidity: ");
                  Serial.println(values["humidity"].as<float>());
                  humidity = values["humidity"].as<float>();
                }
                
                if (values.containsKey("windSpeed")) {
                  Serial.print("Wind Speed: ");
                  Serial.println(values["windSpeed"].as<float>());
                  windSpeed = values["windSpeed"].as<float>();
                }

                if (values.containsKey("precipitationProbability")) {
                  Serial.print("precipitation Probability: ");
                  Serial.println(values["precipitationProbability"].as<float>());
                  precipitationProbability = values["precipitationProbability"].as<float>();
                }
              }
            }
          }
        } else {
          Serial.printf("Error code: %d\n", httpCode);
        }
        success = true;
        https.end();
      }
};
