#include <WiFi.h>
#include <WiFiClientSecure.h>

#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""

WiFiClientSecure client;

#define TEST_HOST "www.hellowatt.fr" 


void setup() {//**********************************SETUP******************

  Serial.begin(115200);

  // Connect to the WiFI
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  Serial.print("Connecting Wifi: ");
  Serial.println(WIFI_SSID);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  IPAddress ip = WiFi.localIP();
  Serial.println(ip);

  client.setInsecure();
  HTTPRequest();
  
}


void loop() {//*************************************LOOP******************
  
}

//**************************************************************************
String find( char* target,  char fintarget) {
  char result[256];
   

  if (!client.find(target)) {
    Serial.println(F("pas trouve"));
    return "";
  } else {
    size_t bytesRead = client.readBytesUntil(fintarget, result, sizeof(result) - 1);
    if (bytesRead > 0) {
      result[bytesRead] = '\0'; // Assurer la terminaison de la chaîne
      return String(result);
    }
  }
  return "";
}

void HTTPRequest() {

  // Opening connection to server (Use 80 as port if HTTP)
  if (!client.connect(TEST_HOST, 443))
  {
    Serial.println(F("Échec de la connexion"));
    return;
  }
  client.print(F("GET "));
  client.print("/ejp-demain-observatoire-edf/");
  client.println(F(" HTTP/1.1"));
  client.print(F("Host: "));
  client.println(TEST_HOST);
  client.println(F("Cache-Control: no-cache"));
  if (client.println() == 0)
  {
    Serial.println(F("Échec de l'envoi de la requête"));
    return;
  }
  
  char status[32] = {0};
  client.readBytesUntil('\r', status, sizeof(status));
  if (strcmp(status, "HTTP/1.1 200 OK") != 0)
  {
    Serial.print(F("Réponse inattendue: "));
    Serial.println(status);
    return;
  }
  char endOfHeaders[] = "\r\n\r\n";
  if (!client.find(endOfHeaders))
  {
    Serial.println(F("response invalide"));
    return;
  }
  String DateToday=find(">Aujourd&#x27;hui</span>",'<');
  String ejpDataToday=find("class=\"is-ejp\">",'<');
  String ejpPrixToday=find(" aujourd'hui :",'h');
  String DateDemain=find(">Demain</span>",'<');
  String ejpDataDemain=find("class=\"is-ejp\">",'<');
  if (ejpDataToday == "Jour non EJP"){
      ejpDataToday = "Jour vert";
  }else{ejpDataToday = "Jour Rouge";}
  Serial.print("Aujourd hui ");
  Serial.print(DateToday); 
  Serial.print(ejpDataToday); 
  Serial.print(" au prix de ");
  Serial.println(ejpPrixToday); 
  
  Serial.print("Demain ");
  Serial.print(DateDemain); 
  Serial.println(ejpDataDemain);  
    
  
}