#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#define LED_BUILTIN 2 
const char* ssid_sta = "Wokwi-GUEST"; // Nome da rede Wi-Fi externa (STA)
const char* password_sta = "";  // Senha da rede Wi-Fi externa (STA)
const char* ssid_ap = "ESP32_AP";        // Nome da rede Wi-Fi do AP
const char* password_ap = "senhaap";     // Senha do AP
WebServer server(80);
void setup() {
  Serial.begin(115200);
  
  // Configuração do modo STA (conectar a uma rede Wi-Fi externa)
  WiFi.mode(WIFI_AP_STA);  // Habilita tanto o AP quanto o STA ao mesmo tempo
  
  // Configura o modo STA e conecta à rede Wi-Fi externa
  Serial.println("Conectando-se à rede Wi-Fi...");
  WiFi.begin(ssid_sta, password_sta);
  // Espera até conectar-se ao Wi-Fi (STA)
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println();
  Serial.print("Conectado à rede Wi-Fi, IP: ");
  Serial.println(WiFi.localIP());  // Mostra o IP atribuído ao ESP32 na rede externa
  
  // Configuração do modo AP
  WiFi.softAP(ssid_ap, password_ap);  // Configura a rede AP
  Serial.print("Ponto de Acesso iniciado, IP do AP: ");
  Serial.println(WiFi.softAPIP());    // Mostra o IP do AP
  pinMode(LED_BUILTIN, OUTPUT);
  server.on("/", handleRoot);
  
  server.on("/on", handleOn);
  
  server.on("/off", handleOff);
  
  /*server.on("/inline", []() {
   server.send(200, "text/plain", "this works as well");
  });*/
  
  server.onNotFound(handleNotFound);
  
  server.begin();
  Serial.println("HTTP server started");
  
}
void loop() {
  server.handleClient();
  delay(2);//allow the cpu to switch to other tasks
  // Aqui você pode colocar código adicional para interagir com o AP ou STA
  // O ESP32 pode atuar como servidor para dispositivos conectados ao AP
  // E também se comunicar com a internet ou outros dispositivos pela rede STA
  //delay(5000);  // Pausa de 5 segundos
}
void handleRoot() {
 String html = "";
 html+= "<style>a {font-size:40px; background-color:#CCCCCC;}</style>";
 html+= "<meta charset='UTF-8'>";
 html += "<h1>Exemplo SoftAP IFRJ campus Niterói</h1>";
 html += "Clique <a href=\"/on\">aqui</a> para ligar o LED.<br><br><br>";
 html += "Clique <a href=\"/off\">aqui</a></h2> para desligar o LED.";
 html += "<h3>Autor: Luiz Oliveira</h3>";
 server.send(200, "text/html", html);
}
 
void handleOn() {
 digitalWrite(LED_BUILTIN, 1);
 handleRoot();
}
 
void handleOff() {
 digitalWrite(LED_BUILTIN, 0);
 handleRoot();
}
 
void handleNotFound() {
 digitalWrite(LED_BUILTIN, 1);
 String message = "File Not Found\n\n";
 message += "URI: ";
 message += server.uri();
 message += "\nMethod: ";
 message += (server.method() == HTTP_GET) ? "GET" : "POST";
 message += "\nArguments: ";
 message += server.args();
 message += "\n";
 for (uint8_t i = 0; i < server.args(); i++) {
   message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
 }
 server.send(404, "text/plain", message);
 digitalWrite(LED_BUILTIN, 0);
}