#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266SSDP.h>

#include "ProjGlobals.h"        // Some global settings
#include "WiFiConfiguration.h"  // 
#include "WiFiStateHandler.h"   // Startup as AP or client and transition
#include "CustomHandlers.h"     // Handlers for the web pages
#include "PlantModel.h"			// The Plant Model controller/simulator/status

const String AP_NAME = "GrowController";    ///< Network name when in Access Point mode
const String AP_VERS = "v1.00.11";          ///< Compared to the server version for SW Updates

ESP8266WebServer server(80);
ConfigManager wifiConfig;        ///< Track various configuration items

//ESP8266HTTPUpdate Updater;
bool updateCheck = false;        ///< Set when a SW update check is pending


// Register the urls with custom handlers
// Register the SSDP interface 
//
void StartWebServer();


void setup() {
  Serial.begin(115200);
  Serial.printf("\n");
  Serial.printf("\n******************************************************************\n");
  Serial.printf(" %s Web Server - Build " __DATE__ " " __TIME__ "\n", AP_NAME.c_str());
  Serial.printf("                                             Version %s\n", AP_VERS.c_str());
  Serial.printf(" Copyright (c) 2021 by Smartware Computing, all rights reserved.\n");
  Serial.printf("******************************************************************\n");
  wifiConfig.load();
}



void loop() {
  //
  // Process WiFi State Changes
  //
  static WiFiConnectState lastState = WFC_Idle;
  WiFiConnectState currState = WiFiStateHandler();
  if (lastState != currState) {
    lastState = currState;
    switch (currState) {    // On change to this state
      default:
        break;
      case WFC_HostingAP:
      case WFC_JoinedAP:
        StartWebServer();
        break;
    }
  } else {
    switch (currState) {
      default:
        break;
      case WFC_HostingAP:
      case WFC_JoinedAP:
        server.handleClient();
        break;
    }
  }

  //
  //
  //
  simulation();
  // @todo delay(1);
}

void StartWebServer() {
  // path /firmware
  Serial.println("HTTP server starting ...");
  //httpUpdater.setup(&server, update_path, update_username, update_password);
  server.on("/",					HandleRootPage);
  server.on("/config",				HandleAPConfigPage);
  server.on("/myip.js",				HandleMyIP_js);
  server.on("/nav.js",				HandleNav_js);
  server.on("/plantmodel.png",		HandlePlantModel);
  server.on("/plantmodel.css",		HandlePlantModel_css);
  server.on("/button.css",			HandleButton_css);
  server.on("/index.js",			HandleIndex_js);
  server.on("/about.htm",			HandleAbout_htm);
  server.on("/about.js",			HandleAbout_js);
  server.on("/favicon.ico",			HandleFavIcon);
  server.on("/soilheater_on.png",	HandleHeaterOn);
  server.on("/soilheater_off.png",	HandleHeaterOff);
  server.on("/thermometer.png",		HandleThermometer);
  server.on("/soilmoisture.png",	HandleSoilMoisture);
  server.on("/pointer.png",			HandlePointer);
  server.on("/water.png",			HandleWater);
  server.on("/green1x1.png",		HandleGreen1x1);
  server.on("/rssi.htm",			HandleRSSIPage);
  server.on("/rssi.js",				HandleRSSI_js);
  server.on("/curr.htm",			HandleCurrPage);
  server.on("/curr.js",				HandleCurr_js);
  server.on("/icon.png",			HandleIcon);
  server.on("/open.png",			HandleOpenDoor);
  server.on("/swupdatecheck", 		HandleSWUpdateCheck);
  server.on("/scan",				HandleAPScan);
  //server.on("/on",				HandleCircuitOn);
  //server.on("/off",				HandleCircuitOff);
  //server.on("/toggle",			HandleCircuitToggle);
  server.on("/state",				HandleGetState);
  server.on("/description.xml", HTTP_GET, []() {
    Serial.printf("description.xml handler.\n");
    SSDP.schema(server.client());
  });
  server.onNotFound(HandleNotFound);
  server.begin();
  Serial.println("HTTP server started.");

  //
  // SSDP Startup
  //
  Serial.printf("SSDP server starting ...\n");
  SSDP.setSchemaURL("description.xml");
  SSDP.setHTTPPort(80);
  SSDP.setName(wifiConfig.getName().c_str());   // "Philips hue clone");
  SSDP.setSerialNumber("001788102201");
  SSDP.setURL("/");     // Root Page
  SSDP.setModelName(AP_NAME.c_str());   // "Philips hue bridge 2012");
  SSDP.setModelNumber("929000226503");
  SSDP.setModelURL("https://www.smart-family.net/GrowController");
  SSDP.setManufacturer("Smartware Computing");
  SSDP.setManufacturerURL("https://www.smart-family.net");
  SSDP.setDeviceType("upnp:rootdevice");
  SSDP.begin();
  Serial.println("SSDP server started.");
}

void FactoryReset(bool forceRestart) {
  Serial.println("Factory Reset Configuration...\n");
  wifiConfig.factoryReset();
  wifiConfig.save();
  if (forceRestart) {
    Serial.println("Restart in 3 sec ...");
    delay(3000);
    ESP.restart();
  }
}
