/*
 * Stairs
 * Copyright 2017 (c) Mark van Renswoude
 *
 * https://git.x2software.net/pub/Stairs
*/
#include "./firmware.h"
#include "../config.h"
#include "../debug.h"
#include "../global.h"



void handleFirmware(AsyncWebServerRequest *request)
{
  shouldReboot = !Update.hasError();

  AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", shouldReboot ? "OK" : "FAIL");
  response->addHeader("Connection", "close");
  request->send(response);
}

void handleFirmwareFile(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final)
{
  _d("Firmware :: file upload: index = "); _d(index);
  _d(", len = "); _d(len);
  _d(", final = "); _dln(final);

  if (!index)
  {
    uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
    _d("Firmware :: update start, max sketch space: ");
    _dln(maxSketchSpace);

    Update.runAsync(true);
    if (!Update.begin(maxSketchSpace))
    {
      #ifdef SerialDebug
      Update.printError(Serial);
      #endif
    }
  }

  if (!Update.hasError())
  {
    if (Update.write(data, len) != len)
    {
      #ifdef SerialDebug
      Update.printError(Serial);
      #endif
    }
  }

  if (final)
  {
    if (Update.end(true))
    {
      _dln("Firmware :: success");
    }
    else
    {
      _dln("Firmware :: failed");
      #ifdef SerialDebug
      Update.printError(Serial);
      #endif
    }
  }
}


void registerFirmwareRoutes(AsyncWebServer* server)
{
  server->on("/api/firmware", HTTP_POST, handleFirmware, handleFirmwareFile);
}