#include "power_manager.h"
#include "config.h"
#include <WiFi.h>
#include <esp_wifi.h>
#include <esp_bt.h>
#include <esp_sleep.h>

static constexpr float BATTERY_DIVIDER = 2.0f;
static constexpr float BATTERY_CAL = 1.0f;
static constexpr float ADC_REF_V = 3.3f;

void power_sender_init() {
  esp_wifi_stop();
  btStop();
  analogReadResolution(12);
  pinMode(PIN_BAT_ADC, INPUT);
}

void power_receiver_init() {
  btStop();
  analogReadResolution(12);
  pinMode(PIN_BAT_ADC, INPUT);
}

void read_battery(MeterData &data) {
  const int samples = 8;
  uint32_t sum = 0;
  for (int i = 0; i < samples; ++i) {
    sum += analogRead(PIN_BAT_ADC);
    delay(5);
  }
  float avg = static_cast<float>(sum) / samples;
  float v = (avg / 4095.0f) * ADC_REF_V * BATTERY_DIVIDER * BATTERY_CAL;

  data.battery_voltage_v = v;
  data.battery_percent = battery_percent_from_voltage(v);
}

uint8_t battery_percent_from_voltage(float voltage_v) {
  float pct = (voltage_v - 3.0f) / (4.2f - 3.0f) * 100.0f;
  if (pct < 0.0f) {
    pct = 0.0f;
  }
  if (pct > 100.0f) {
    pct = 100.0f;
  }
  return static_cast<uint8_t>(pct + 0.5f);
}

void light_sleep_ms(uint32_t ms) {
  if (ms == 0) {
    return;
  }
  esp_sleep_enable_timer_wakeup(static_cast<uint64_t>(ms) * 1000ULL);
  esp_light_sleep_start();
}

void go_to_deep_sleep(uint32_t seconds) {
  esp_sleep_enable_timer_wakeup(static_cast<uint64_t>(seconds) * 1000000ULL);
  esp_deep_sleep_start();
}
