#ifndef OWM_H
#define OWM_H

#include <HTTPClient.h>
#include <ArduinoJson.h>


#define OPENWEATHER_URL(loc, api) ("https://api.openweathermap.org/data/2.5/weather?q=" + loc + "&appid=" + api + "&units=metric")


class OWM{
  public:
    OWM(){};
    OWM(String l,String k) : location(l), key(k){}

    StaticJsonDocument<1024> weather; 
    bool valid_weather = false;

    bool update(){
        String response = httpGETRequest(OPENWEATHER_URL(location,key).c_str());
        DeserializationError error = deserializeJson(weather, response);

        if (error) {
            valid_weather = false;
            return false;
        }

        if(weather["weather"]==NULL ||weather["main"]==NULL ||
            weather["wind"]==NULL || weather["sys"]==NULL ){
            valid_weather = false;
            return false;
        }
        valid_weather = true;
        return true;
    }


    String location;
private:
    String key;

    String httpGETRequest(const char* serverName) {
        HTTPClient http;    
        http.begin(serverName,root_ca);
        int httpResponseCode = http.GET();
        String payload = "{}";
        if (httpResponseCode == HTTP_CODE_OK) {
            payload = http.getString();
        }
        http.end();

        return payload;
    }

    const char* root_ca= \
" -----BEGIN CERTIFICATE-----\n\
MIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhkiG9w0BAQwFADCB\n\
iDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl\n\
cnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV\n\
BAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAw\n\
MjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNV\n\
BAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU\n\
aGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBSU0EgQ2Vy\n\
dGlmaWNhdGlvbiBBdXRob3JpdHkwggI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