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

bool ledOn = false;
const int sensorPin = A0;
const int ledPin = D1;
const char *ssid = "IUT-City";
const char *password = "";
String temp = "\
<!DOCTYPE html>\
<html>\
  <body>\
    <center>\
      <h3>\
        Moisture Level : $moisture$%\
      </h3>\
      <a href=\"$address$\">\
        <button>$button$</button>\
      </a>\
    </center>\
  </body>\
</html>";

ESP8266WebServer server(80);

void handleRoot() {
  int moisture = analogRead(sensorPin);
  moisture = constrain(moisture, 200, 1000);
  moisture = map(moisture, 200, 1000, 100, 0);
  
  String response = temp;
  response.replace("$moisture$", String(moisture));
  if (ledOn)
  {
    response.replace("$address$", "/stop");
    response.replace("$button$", "Stop watering");
  }
  else
  {
    response.replace("$address$", "/start");
    response.replace("$button$", "Start watering");
  }
  
  server.send(200, "text/html", response);
}

void startWatering() {
  ledOn = true;
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, HIGH);
  handleRoot();
  Serial.println("Started watering.");
}

void stopWatering() {
  ledOn = false;
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  handleRoot();
  Serial.println("Stoped watering.");
}

void setup() {
  pinMode(sensorPin, INPUT);
  pinMode(ledPin, OUTPUT);
  pinMode(ledPin, LOW);
 
  Serial.begin(115200);
 
  Serial.print("\nConnecting to ");
  Serial.println(ssid);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (MDNS.begin("esp8266")) {
    Serial.println("MDNS responder started");
  }
  
  server.on("/", handleRoot);
  server.on("/start", startWatering);
  server.on("/stop", stopWatering);
  server.begin();
  Serial.println("HTTP server started");
}

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