const byte led = D1;
const byte button = D5;
bool LEDstate = false;

#include <ESP8266WiFi.h>

#define WIFI_MODE_CLIENT //can be WIFI_MODE_MASTER

// Replace with your network credentials
char* ssid = "WIV"; //"DasSchmalter";
char* password = "DF~12qa.40"; //"12345678";


// Set web server port number to 80
WiFiServer server(80);

String header;
// the code for the whole ebinterface
String webInterface = "<!DOCTYPE html>\n<html lang=\"de\">\n\n<head>\n\n<meta charset=\"utf-8\" />\n\n<title>Das Schmalter</title>\n\n<style>\n\t\n    h1{\n        text-align: center;\n    }\n\t\n    button{\n\t\twidth: 40%;\n\t    height: 100px;\n\t\tdisplay: block;\n\t\tmargin-left: auto;\n\t\tmargin-right: auto;\n\t\tbackground-color: white;\n\t\tcolor:black;\n\t\tborder: 4px solid #4CAF50;\n\t\tborder-radius: 100px;\n\t\ttransition-duration: 0.8s;\n\t\tfont-size: 200%;\n    }\n    button:hover{\n        background-color:#4CAF50;\n        color:white;\n    }\n\t\n\t.disabled{\n\t\topacity: 0.6;\n\t\tcursor: not-allowed;\n\t}\n\t\n\tdiv{\n\ttext-align:center;\n\tcolor:red;\n\tfont-size: 200%;\n\tmargin-top: 40px;\n\t}\n\t\n</style>\n\n<script>\n\nvar currentState=\"\";\nvar ipAdress = window.location.host;\nfunction getState(){\n\tsendRequest(\"http://\"+ipAdress+\"/api/state\");\n}\n\nfunction requestFinished(){\n\tif(this.readyState === 4 && this.status === 200){\n\t\tif(this.responseText !== \"\"){\n\t\t\n\t\t\tresponseObj = JSON.parse(this.responseText);\n\t\t\t\n\t\t\tif(responseObj[\"command\"] == \"state\"){\n\t\t\t\t\n\t\t\t\tcurrentState = responseObj[\"response\"];\n\t\t\t\t\n\t\t\t\tif(currentState == 'OFF'){\n\t\t\t\t\t\n\t\t\t\t\tdocument.getElementById(\"toggleLightBt\").classList.remove(\"disabled\");\n\t\t\t\t\t\n\t\t\t\t\tdocument.getElementById(\"toggleLightBt\").innerHTML = \"Turn on\";\n\t\t\t\n\t\t\t\t\tdocument.getElementById(\"errorDiv\").innerHTML = \"\";\n\t\t\t\t}\n\t\t\t\n\t\t\t\telse if(currentState == 'ON'){\n\t\t\t\t\t\n\t\t\t\t\tdocument.getElementById(\"toggleLightBt\").classList.remove(\"disabled\");\n\t\t\t\t\t\n\t\t\t\t\tdocument.getElementById(\"toggleLightBt\").innerHTML = \"Turn off\";\n\t\t\t\n\t\t\t\t\tdocument.getElementById(\"errorDiv\").innerHTML = \"\";\n\t\t\t\t}\n\t\t\t\n\t\t\t\telse{\n\t\t\t\t\t\n\t\t\t\t\tdocument.getElementById(\"toggleLightBt\").classList.add(\"disabled\");\n\t\t\t\t\t\n\t\t\t\t\tdocument.getElementById(\"toggleLightBt\").innerHTML = \"ERROR\";\n\t\t\t\t\t\n\t\t\t\t\tdocument.getElementById(\"errorDiv\").innerHTML = \"Unkwon error while connecting to Das Schmalter\";\n\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\n\t\t}\n\t}\n\telse if(this.readyState == 4){\n\t\tdocument.getElementById(\"toggleLightBt\").classList.add(\"disabled\");\n\t\tdocument.getElementById(\"errorDiv\").innerHTML = \"Error while connecting to Das Schmalter: \"+this.status\n\t}\n}\n\nfunction toggleLigth(){\n\tif(document.getElementById(\"toggleLightBt\").classList.contains(\"disabled\")){\n\t\treturn;\n\t}\n\tif(currentState == 'OFF'){\n\t\tsendRequest(\"http://\"+ipAdress+\"/api/on\")\n\t}\n\telse if(currentState == 'ON'){\n\t\tsendRequest(\"http://\"+ipAdress+\"/api/off\")\n\t}\n\telse{\n\t\talert(\"ERROR! \" + currentState);\n\t}\n\tgetState();\n}\nfunction sendRequest(link){\n    xmlhttp = new XMLHttpRequest();\n    xmlhttp.onreadystatechange = requestFinished;\n    xmlhttp.open(\"GET\", link, true);\n    xmlhttp.send();\n}\n\nsetInterval(function(){getState();},200)\n\n</script>\n\n</head>\n\n<body>\n\n<h1>Das Schmalter</h1>\n\n<div style=\"height:50px\"></div>\n\n<a><button id=\"toggleLightBt\" class=\"disabled\" onclick=\"toggleLigth()\">Turn on</button></a>\n\n<div id=\"errorDiv\"></div>\n\n</body>\n\n</html>";

// Configure the static ip adress
#ifdef WIFI_MODE_CLIENT
IPAddress local_IP(192, 168, 4, 10);
#endif
#ifdef WIFI_MODE_MASTER
IPAddress local_IP(192, 168, 4, 1);
#endif
IPAddress gateway(192, 168, 4, 1);
IPAddress subnet(255, 255, 255, 0);

volatile unsigned long oldTime = 0, debounceTime = 200;
void toggleLED() {
  if ((millis() - oldTime) > debounceTime) {
    
    if (digitalRead(button) == LOW) {
      LEDstate = ! LEDstate;
      digitalWrite(led, LEDstate);
    }
  }
  oldTime = millis();
}

void setup() {
  // put your setup code here, to run once:
  pinMode(led, OUTPUT);
  pinMode(button, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(button), toggleLED, FALLING);
  Serial.begin(9600);

  /*if (!WiFi.config(local_IP, gateway, subnet)) {
    //Serial.println("STA Failed to configure");
  } */
#ifdef WIFI_MODE_MASTER
  //Serial.print("Configuring access point...");
  //WiFi.softAPConfig(local_IP, gateway, subnet);
  WiFi.softAP(ssid, password);

  IPAddress myIP = WiFi.softAPIP();
  //Serial.print("AP IP address: ");
  //Serial.println(myIP);
#endif

#ifdef WIFI_MODE_CLIENT
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi..");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("Connected to the WiFi network");
  Serial.println(WiFi.localIP());
#endif

  server.begin();
}


void loop() {
  // put your main code here, to run repeatedly:
  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    //Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        //Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Access-Control-Allow-Origin: *");
            client.println("Connection: close");
            client.println();

            // turns the GPIOs on and off
            if (header.indexOf("GET /api/on") >= 0) {
              //Serial.println("LAMP on");
              LEDstate = true;
              digitalWrite(led, HIGH);
              client.println("{\"command\":\"on\",\"response\":\"OK\"}");
            } else if (header.indexOf("GET /api/off") >= 0) {
              //Serial.println("LAMP off");
              LEDstate = false;
              digitalWrite(led, LOW);
              client.println("{\"command\":\"off\",\"response\":\"OK\"}");
            } else if (header.indexOf("GET /api/state") >= 0) {
              if(LEDstate) {
                client.println("{\"command\":\"state\",\"response\":\"ON\"}");
              }
              else {
                client.println("{\"command\":\"state\",\"response\":\"OFF\"}");
              }
              //Serial.println("LAMP status");
            }
            else {
              // Display the HTML web page
              client.println(webInterface);

            }



            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    //Serial.println("Client disconnected.");
    //Serial.println("");
  }
}
