#include <WiFi.h>
#include <WebServer.h>
#include "esp_wifi.h"

const char* ssid = "ESP32-Louis";
const char* password = "motdepasse";

WebServer server(80);

void handleRoot() {
  digitalWrite(2,HIGH);
  wifi_sta_list_t sta_list;
  esp_wifi_ap_get_sta_list(&sta_list);

  String page = "";
  page += "<!DOCTYPE html>";
  page += "<html>";
  page += "<head>";
  page += "<title>ESP32</title>";
  page += "<meta charset=\"UTF-8\">";
  page += "</head>";
  page += "<body>";
  page += "<h1>Appareils connectés à l'ESP32</h1>";
  page += "<ul>";

  page += "<ul>";

  for (int i = 0; i < sta_list.num; i++) {
    const wifi_sta_info_t& client = sta_list.sta[i];
    char macStr[18];
    snprintf(macStr, sizeof(macStr),
             "%02X:%02X:%02X:%02X:%02X:%02X",
             client.mac[0], client.mac[1], client.mac[2],
             client.mac[3], client.mac[4], client.mac[5]);
    page += "<li>MAC : ";
    page += macStr;
    page += "</li>";
  }

  page += "</ul>";
  page += "<p>Nombre total : " + String(sta_list.num) + "</p>";

  page += "</body></html>";

  server.send(200, "text/html", page);
  digitalWrite(2,LOW);
}

void onClientConnected(WiFiEvent_t event, WiFiEventInfo_t info) {
  digitalWrite(2,HIGH);

  wifi_sta_list_t sta_list;
  esp_wifi_ap_get_sta_list(&sta_list);

  for (int i = 0; i < sta_list.num; i++) {
    const wifi_sta_info_t& client = sta_list.sta[i];
    char macStr[18];
    snprintf(macStr, sizeof(macStr),
             "%02X:%02X:%02X:%02X:%02X:%02X",
             client.mac[0], client.mac[1], client.mac[2],
             client.mac[3], client.mac[4], client.mac[5]);
    Serial.print("Adresse MAC : ");
    Serial.println(macStr);
  }

  digitalWrite(2,LOW);
}

void onClientDisconnected(WiFiEvent_t event, WiFiEventInfo_t info) {
  digitalWrite(2,HIGH);
  
  wifi_sta_list_t sta_list;
  esp_wifi_ap_get_sta_list(&sta_list);

  for (int i = 0; i < sta_list.num; i++) {
    const wifi_sta_info_t& client = sta_list.sta[i];
    char macStr[18];
    snprintf(macStr, sizeof(macStr),
             "%02X:%02X:%02X:%02X:%02X:%02X",
             client.mac[0], client.mac[1], client.mac[2],
             client.mac[3], client.mac[4], client.mac[5]);
    Serial.print("",macStr);
  }

  digitalWrite(2,LOW);
}

void setup() {
  Serial.begin(115200);
  WiFi.softAP(ssid, password);

  WiFi.onEvent(onClientConnected, ARDUINO_EVENT_WIFI_AP_STACONNECTED);
  WiFi.onEvent(onClientDisconnected, ARDUINO_EVENT_WIFI_AP_STADISCONNECTED);

  delay(1000);  // Donne un peu de temps pour démarrer le WiFi


  server.on("/", handleRoot);
  server.begin();

  pinMode(2, OUTPUT);
}

void loop() {
  server.handleClient();
}