#include "deep_sleep_component.h"
#ifdef USE_ZEPHYR
#include "esphome/core/log.h"
#include "esphome/core/wake.h"
#include <zephyr/sys/poweroff.h>

namespace esphome::deep_sleep {

static const char *const TAG = "deep_sleep";

optional<uint32_t> DeepSleepComponent::get_run_duration_() const { return this->run_duration_; }

void DeepSleepComponent::dump_config_platform_() {}

bool DeepSleepComponent::prepare_to_sleep_() { return true; }

void DeepSleepComponent::deep_sleep_() {
  if (this->sleep_duration_.has_value()) {
    esphome::internal::wakeable_delay(static_cast<uint32_t>(*this->sleep_duration_ / 1000));
  } else {
#ifndef USE_ZIGBEE
    // the device can be woken up through one of the following signals:
    // - The DETECT signal, optionally generated by the GPIO peripheral.
    // - The ANADETECT signal, optionally generated by the LPCOMP module.
    // - The SENSE signal, optionally generated by the NFC module to wake-on-field.
    // - Detecting a valid USB voltage on the VBUS pin (VBUS,DETECT).
    // - A reset.
    //
    // The system is reset when it wakes up from System OFF mode.
    sys_poweroff();
#else
    esphome::internal::wakeable_delay(UINT32_MAX);
#endif
  }
  const bool woke = esphome::wake_request_take();
  if (woke) {
    ESP_LOGD(TAG, "Woken up by another thread");
  } else {
    ESP_LOGD(TAG, "Timeout expired (normal sleep)");
  }
}

bool DeepSleepComponent::should_teardown_() {
  if (this->sleep_duration_.has_value()) {
    return false;
  }
#ifdef USE_ZIGBEE
  return false;
#else
  return true;
#endif
}

}  // namespace esphome::deep_sleep

#endif
