/**************************************************
 Übung: ESP32 (Teil 2) - Aufgabe 5 (Vorlage)
***************************************************/

//-----------------------------------------------------------
#include <WiFi.h>
#include <WebServer.h>

//-----------------------------------------------------------
// BBWAS1:
const int PIN_LED_RGB_ROT = 13;

// Statusvariablen
int status_led_rgb_rot = 0;

//-----------------------------------------------------------
// WiFi:
const char WIFI_SSID[] = "m126";
const char WIFI_PASSWORD[] = "M126M126";

// Webserver Objekt (Port 80)
WebServer webserver(80);

//-----------------------------------------------------------
void setup(void) {
  //---
  // UART starten (115200 Baud)
  Serial.begin(115200);

  //---
  // WiFi verbinden
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Verbinde mit ");
  Serial.print(WIFI_SSID);

  // Warten bis mit WiFi verbunden...
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(100);
  }
  Serial.println(" Verbunden!");

  // Zugewiesene IP-Adresse ausgeben
  Serial.print("IP-Adresse: ");
  Serial.println(WiFi.localIP());

  //---
  // Webserver URL konfigurieren
  webserver.on("/", handle_page_index);

  // Webserver starten
  webserver.begin();
  Serial.println("Webserver gestartet!");
}

//-----------------------------------------------------------
void loop(void) {
  // Webserver bedienen
  webserver.handleClient();
  delay(10);
}

//-----------------------------------------------------------
void handle_page_index() {
  //---
  // Query-Parameter "rot" behandeln
  if (webserver.hasArg("rot") == true) {
    String p = webserver.arg("rot");
    //
    Serial.print("rot=");
    Serial.println(p);
    //
    status_led_rgb_rot = p.toInt();
    analogWrite(PIN_LED_RGB_ROT, status_led_rgb_rot);
  }

  //---
  // HTML-Template
  String html_template = R"(
    <!DOCTYPE html>
    <html>
      <head>
        <title>ESP32 Webserver</title>
      </head>
            
      <body>
        <h1>ESP32 Webserver</h1>

        <div>
          <h2>RGB LED - ROT</h2>
          <p>Aktueller Status: *RGB_ROT_TEXT*</p>
          
          <form method="get" action="/">
            <input type="range" name="rot" min="0" max="255" step="1" value="*RGB_ROT_VALUE*">
            <br><br>
            <button type="submit"> Send </button>
          </form>

        </div>
      </body>
    </html>
  )";

  //---
  // HTML-Template updaten
  html_template.replace("*RGB_ROT_TEXT*", String(status_led_rgb_rot));
  html_template.replace("*RGB_ROT_VALUE*", String(status_led_rgb_rot));

  //---
  // HTML an Client senden
  webserver.send(200, "text/html", html_template);
}