#include "ota.h"
#include "config.h"
#include "certs.h"
#include "led.h"
#include <NetworkClientSecure.h>
#include <HTTPUpdate.h>
#if ENABLE_LAN_OTA
#include <ArduinoOTA.h>
#endif

namespace ota {
  void beginLan(const String& hostname) {
#if ENABLE_LAN_OTA
    ArduinoOTA.setHostname(hostname.c_str());
    ArduinoOTA.onStart([]() { led::set(LED_CONNECTING); });
    ArduinoOTA.begin();
#else
    (void)hostname;
#endif
  }
  void loopLan() {
#if ENABLE_LAN_OTA
    ArduinoOTA.handle();
#endif
  }
  bool pull(const String& url) {
    NetworkClientSecure client;
    client.setCACert(ROOT_CA_PEM);
    led::set(LED_CONNECTING);
    httpUpdate.rebootOnUpdate(true);
    t_httpUpdate_return r = httpUpdate.update(client, url);
    if (r == HTTP_UPDATE_FAILED) {
      Serial.printf("[ota] failed: %s\n", httpUpdate.getLastErrorString().c_str());
      led::settle(LED_ERROR, 2000, LED_IDLE);
      return false;
    }
    return r == HTTP_UPDATE_NO_UPDATES;
  }
}
