#include "blinkhttp.h"

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

// WIFI
WiFiClient espClient;

// HTTP
ESP8266WebServer server(HTTP_PORT);

void setup()
{
  Serial.begin(SERIAL_SPEED);
  Serial.println("\nresetting");
  
  // LED
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, 0);
  
  // WIFI
  setupWifi();
  
  // HTTP
  setupHTTP();
}

// WIFI
void setupWifi() {
  Serial.print("Connexion a ");
  Serial.print(wifi_ssid);
  WiFi.begin(wifi_ssid, wifi_password);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  
  Serial.println();
  Serial.print("IP : ");
  Serial.println(WiFi.localIP());

  if (MDNS.begin("esp8266")) {
    Serial.println("MDNS responder started");
  }
}

// HTTP
void setupHTTP()
{
  server.on("/", handleRoot);

  server.on("/inline", [](){
    server.send(200, "text/plain", "this works as well");
  });

  server.onNotFound(handleNotFound);

  server.begin();
  Serial.println("HTTP server started");
}

void handleRoot()
{
  digitalWrite(LED_PIN, 1);
  server.send(200, "text/plain", "hello from esp8266!");
  delay(500);
  digitalWrite(LED_PIN, 0);
}

void handleNotFound()
{
  digitalWrite(LED_PIN, 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_PIN, 0);
}

void loop()
{
  server.handleClient();
}
