#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 ejpDataToday=find("class=\"is-ejp\">",'<');
  Serial.print("Aujourd hui ");
  Serial.print(ejpDataToday); 
  Serial.print(" au prix de ");
  String ejpPrixToday=find(" aujourd'hui :",'h');
  Serial.print(ejpPrixToday); 
  Serial.println("h"); 
   
  String ejpDataDemain=find("class=\"is-ejp\">",'<');
  Serial.print("Demain ");
  Serial.println(ejpDataDemain);  
  
}