#ifndef WEB_HANDLERS_H
#define WEB_HANDLERS_H

#include "Config.h"

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <Updater.h>
#include <EEPROM.h>

#include "Global.h"
#include "WebPages.h"

// -------------------- ROOT --------------------
inline void handleRoot() {
  if (WiFi.getMode() == WIFI_AP)
    return server.send(200, "text/html", wifiSetupPage);

  String msg = "ESP8266 (-01S) WiFi Relay\nID: " + getUniqueID() + "\nVersion: ";
  msg += FW_VERSION;

  server.send(200, "text/plain", msg);
}

// -------------------- SAVE WIFI --------------------
inline void handleSaveWiFi() {
  String ssid = server.arg("ssid");
  String pass = server.arg("pass");

  savedSSID = ssid;
  savedPASS = pass;
  saveWiFiConfig(savedSSID, savedPASS);

  server.send(200, "text/plain", "Saved! Rebooting...");
  delay(800);
  ESP.restart();
}

// -------------------- OTA PAGES --------------------
inline void handleUpdateGet() {
  server.send(200, "text/html", updatePage);
}

inline void handleUpdateUpload() {
  HTTPUpload& upload = server.upload();

  if (upload.status == UPLOAD_FILE_START) {
    Serial.printf("OTA start: %s\n", upload.filename.c_str());

    size_t sketchSpace = (ESP.getFreeSketchSpace() - 0x2000) & 0xFFFFF000;

    if (!Update.begin(sketchSpace)) { // более безопасный вариант
      Update.printError(Serial);
    }
  }
  else if (upload.status == UPLOAD_FILE_WRITE) {
    if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
      Update.printError(Serial);
    }
  }
  else if (upload.status == UPLOAD_FILE_END) {
    if (!Update.end(true)) {   // true = сразу перезаписать раздел
      Update.printError(Serial);
    }
  }
}

inline void handleUpdatePost() {
  if (Update.hasError()) server.send(200, "text/plain", "Update Failed!");
  else                   server.send(200, "text/plain", "Update OK! Rebooting...");

  delay(800);
  ESP.restart();
}

// -------------------- Регистрация роутов веб-панели --------------------
inline void registerWebUiRoutes() {
  server.on("/",          HTTP_GET,  handleRoot);
  server.on("/save_wifi", HTTP_POST, handleSaveWiFi);
  server.on("/update",    HTTP_GET,  handleUpdateGet);
  server.on("/update",    HTTP_POST, handleUpdatePost, handleUpdateUpload);
}

#endif // WEB_HANDLERS_H
