#include <Arduino.h>
#ifdef ESP32
#include <WiFi.h>
#include <AsyncTCP.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#endif
#include <ESPAsyncWebServer.h>
#include <LittleFS.h>
#include <SPI.h>
#include <SD.h>

const int chipSelect = D8;


/*
  Replace the SSID and Password according to your wifi
*/
const char *ssid = "WIFI_SSID";
const char *password = "PASSWORD";


// Webserver
AsyncWebServer server(80);

String PARAM_MESSAGE = "status";

const int LED_PIN = LED_BUILTIN;

void notFound(AsyncWebServerRequest *request) {
  request->send(404, "text/plain", "Not found");
}

void toggleLED(String status) {
  if (status == "ON")
    digitalWrite(LED_PIN, LOW);
  else
    digitalWrite(LED_PIN, HIGH);
}

void addRoute(String route, String filename, String mimtype) {
  server.on(route.c_str(), HTTP_GET, [filename, mimtype](AsyncWebServerRequest *request) { 
    File file = SD.open(filename);
    request->send(file, filename, mimtype); 
  });
}

void setup()
{

  Serial.begin(115200);
  Serial.println("Starting the LittleFS Webserver..");

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }
  Serial.println("card initialized.");

  // Connect to WIFI
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  if (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.printf("WiFi Failed!\n");
    return;
  }

  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());

  // LED PIN
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);

  addRoute("/", "/index.html", "text/html");
  addRoute("/index.css", "/index.css", "text/css");
  addRoute("/entireframework.min.css", "/entireframework.min.css", "text/css");
  addRoute("/index.js", "/index.js", "text/javascript");


  // Respond to toggle event
  server.on("/toggle", HTTP_GET, [](AsyncWebServerRequest *request) {
    String status;
    if (request->hasParam(PARAM_MESSAGE)) {
        status = request->getParam(PARAM_MESSAGE)->value();
        if(status == "ON"){
          toggleLED("ON");
        } else {
          toggleLED("OFF");
        }
    } else {
        status = "No message sent";
    }
    request->send(200, "text/plain", "Turning Built In LED : " + status); 
  });

  server.onNotFound(notFound);

  server.begin();
}

void loop()
{
}