/*
 * WiFiAccessPointMode.ino
 * 
 * This example demonstrates how to set up an ESP32 as a WiFi Access Point
 * using the WiFiHandlerV2 class. It creates an access point that other
 * devices can connect to.
 */

#include "wifi-handlerv2.h"

// Access Point configuration
const char* ap_ssid = "ESP32_AP";
const char* ap_password = "password123";  // Must be at least 8 characters or NULL for open network

// Create WiFiHandler instance
WiFiHandlerV2 wifi;

// Variables to track connected devices
int lastClientCount = 0;

void setup() {
  Serial.begin(115200);
  delay(1000);
  
  Serial.println("Starting WiFi Access Point Mode example");
  
  // Start the access point
  Serial.print("Creating Access Point: ");
  Serial.println(ap_ssid);
  
  if (wifi.startAP(ap_ssid, ap_password)) {
    Serial.println("Access Point started successfully!");
    printAPInfo();
  } else {
    Serial.println("Failed to start Access Point!");
  }
}

void loop() {
  // Run wifi handler loop
  wifi.loop();
  
  // Check if AP is still active
  if (wifi.isAPActive()) {
    // Monitor the number of connected devices (this requires WiFi.softAPgetStationNum())
    int clientCount = WiFi.softAPgetStationNum();
    
    if (clientCount != lastClientCount) {
      Serial.print("Number of connected devices changed: ");
      Serial.println(clientCount);
      lastClientCount = clientCount;
    }
    
    // Your AP mode logic here
  } else {
    Serial.println("AP has stopped. Restarting...");
    if (wifi.startAP(ap_ssid, ap_password)) {
      Serial.println("Access Point restarted successfully!");
      printAPInfo();
    } else {
      Serial.println("Failed to restart Access Point!");
      delay(5000);
    }
  }
  
  // Other loop code here
  delay(1000);
}

void printAPInfo() {
  Serial.println("===== Access Point Information =====");
  Serial.print("SSID: ");
  Serial.println(ap_ssid);
  
  Serial.print("IP Address: ");
  Serial.println(wifi.getAPIP());
  
  Serial.print("MAC Address: ");
  Serial.println(wifi.getMacAddress());
  
  Serial.print("Security: ");
  Serial.println(ap_password ? "WPA2-PSK" : "Open");
  
  Serial.println("Connect to this Access Point and navigate to http://");
  Serial.print(wifi.getAPIP());
  Serial.println(" in your browser");
  Serial.println("=====================================");
}