#include "ota.h"


void initOTA(const char* hostname) 
{
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    log_e("Connection Failed! Rebooting...");
    delay(5000);
    ESP.restart();
  }

  // Port defaults to 3232
  // ArduinoOTA.setPort(3232);

  // Hostname defaults to esp3232-[MAC]
  ArduinoOTA.setHostname(hostname);

 
  ArduinoOTA
    .onStart([]() {
      String type;
      if (ArduinoOTA.getCommand() == U_FLASH)
        type = "sketch";
      else // U_SPIFFS
        type = "filesystem";

      // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
      log_i("Start updating %s",  type);
    })
    .onEnd([]() {
      log_i("End");
    })
    .onProgress([](unsigned int progress, unsigned int total) {
      log_i("Progress: %u%%\r", (progress / (total / 100)));
    })
    .onError([](ota_error_t error) {
      if (error == OTA_AUTH_ERROR) log_e("Auth Failed");
      else if (error == OTA_BEGIN_ERROR) log_e("Begin Failed");
      else if (error == OTA_CONNECT_ERROR) log_e("Connect Failed");
      else if (error == OTA_RECEIVE_ERROR) log_e("Receive Failed");
      else if (error == OTA_END_ERROR) log_e("End Failed");
      else log_e("unknown error %i", error);
    });

  ArduinoOTA.begin();

  log_i("OTA Ready");
}

void loopOTA() {
  ArduinoOTA.handle();
}