// Learn about the ESP32 WiFi simulation in
// https://docs.wokwi.com/guides/esp32-wifi



//const char* url = "https://www.hellowatt.fr/ejp-demain-observatoire-edf";



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

Ticker animation_ticker;
bool finishedAnimating = false;
bool finishedAnimatingTwo = false;
unsigned long resetAnimationDue = 0;

WiFiClientSecure client;

unsigned long timeBetweenRequests = 60000; // 1 minute
unsigned long apiRequestDue = 0; // When API request is next Due

// ----------------------------
// Config - Replace These
// ----------------------------

// Website we are connecting to
#define HOST_WEBSITE "teamtrees.org"

void setup() {
  Serial.begin(115200);

  // Connect to Wifi before displaying to the screen

  // Attempt to connect to Wifi network:
  Serial.print("Connecting Wifi: ");
  

  // Explicitly set the ESP32 to be a WiFi-client
  WiFi.mode(WIFI_STA);
  WiFi.begin("Wokwi-GUEST", "", 6);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    
    Serial.println("Connexion en cours...");
  }
 
  Serial.println("Connexion etablie !");
 
  int tree = getTreeCount();
  if (tree > 0) {
    Serial.print("Initial #TeamTrees: ");
    Serial.println(tree);
  }

  animation_ticker.attach(0.10, drawStuff);
}

bool timerSet = false;

int getTreeCount() {
  if (client.connected()) {
    client.stop();
  }

  int treeCount = 0;

  // Opening connection to server (Use 80 as port if HTTP)
  if (!client.connect(HOST_WEBSITE, 443)) {
    Serial.println(F("Connection failed"));
    return 0;
  }

  // give the esp a breather
  yield();

  // Send HTTP request
  client.print(F("GET "));
  client.print("/");
  client.println(F(" HTTP/1.1"));

  // Headers
  client.print(F("Host: "));
  client.println(HOST_WEBSITE);

  client.println(F("Cache-Control: no-cache"));

  if (client.println() == 0) {
    Serial.println(F("Failed to send request"));
    return 0;
  }

  // Check HTTP status
  char status[32] = {0};
  client.readBytesUntil('\r', status, sizeof(status));
  if (strcmp(status, "HTTP/1.1 200 OK") != 0) {
    Serial.print(F("Unexpected response: "));
    Serial.println(status);
    return 0;
  }

  // Skip HTTP headers
  char endOfHeaders[] = "\r\n\r\n";
  if (!client.find(endOfHeaders)) {
    Serial.println(F("Invalid response"));
    return 0;
  }

  char treeData[32] = {0};

  // The count for the Tree is a property of the Div that eventually displays the count.
  // the innerHTML of the div starts as 0

  // Skip to the text that comes after "data-count=\""
  char treeString[] = "data-count=\"";
  if (!client.find(treeString)) {
    Serial.println(F("Found no trees"));
    return 0;
  } else {
    // copy the data from the stream til the next "
    client.readBytesUntil('\"', treeData, sizeof(treeData));
    Serial.print("#TeamTrees: ");
    Serial.println(treeData);

    sscanf(treeData, "%d", &treeCount);
  }

  return treeCount;
}

void drawStuff() {
  if (!finishedAnimating) {
    // Step 2: Log tetris state
    Serial.println("Animating...");
  }
}

void loop() {
  if (finishedAnimatingTwo && !timerSet) {
    apiRequestDue = millis() + timeBetweenRequests;
    timerSet = true;
  }

  if (finishedAnimatingTwo && millis() > apiRequestDue) {
    int tree = getTreeCount();
    if (tree > 0) {
      Serial.print("Updated #TeamTrees: ");
      Serial.println(tree);
      finishedAnimating = false;
      finishedAnimatingTwo = false;
    }
    timerSet = false;
  }
}