#pragma once

#include <Arduino.h>
#include <Wire.h>
#include <XPowersLib.h>
#include "Boards.h"

namespace tbeam_supreme {

inline int i2cSda() { return I2C_SDA; }
inline int i2cScl() { return I2C_SCL; }
inline int sdSck() { return SD_CLK; }
inline int sdMiso() { return SD_MISO; }
inline int sdMosi() { return SD_MOSI; }
inline int sdCs() { return SD_CS; }
inline int imuCs() { return IMU_CS; }

inline bool initPmuForPeripherals(XPowersLibInterface*& pmu, Print* out = nullptr) {
  if (BOARD_MODEL != BOARD_TBEAM_S_V1) {
    if (out) out->println("PMU adapter: BOARD_MODEL is not T-Beam Supreme");
    return false;
  }

  Wire1.begin(i2cSda(), i2cScl());

  if (!pmu) {
    pmu = new XPowersAXP2101(Wire1);
  }

  if (!pmu->init()) {
    if (out) out->println("PMU adapter: AXP2101 init failed");
    return false;
  }

  // Match microReticulum_Firmware tbeam supreme rail setup.
  pmu->setPowerChannelVoltage(XPOWERS_ALDO4, 3300);
  pmu->enablePowerOutput(XPOWERS_ALDO4);
  pmu->setPowerChannelVoltage(XPOWERS_ALDO3, 3300);
  pmu->enablePowerOutput(XPOWERS_ALDO3);
  pmu->setPowerChannelVoltage(XPOWERS_DCDC3, 3300);
  pmu->enablePowerOutput(XPOWERS_DCDC3);
  pmu->setPowerChannelVoltage(XPOWERS_ALDO2, 3300);
  pmu->enablePowerOutput(XPOWERS_ALDO2);
  pmu->setPowerChannelVoltage(XPOWERS_ALDO1, 3300);
  pmu->enablePowerOutput(XPOWERS_ALDO1);
  pmu->setPowerChannelVoltage(XPOWERS_BLDO1, 3300);
  pmu->enablePowerOutput(XPOWERS_BLDO1);

  pmu->disablePowerOutput(XPOWERS_DCDC2);
  pmu->disablePowerOutput(XPOWERS_DCDC5);
  pmu->disablePowerOutput(XPOWERS_DLDO1);
  pmu->disablePowerOutput(XPOWERS_DLDO2);
  pmu->disablePowerOutput(XPOWERS_VBACKUP);

  pmu->setChargeTargetVoltage(XPOWERS_AXP2101_CHG_VOL_4V2);
  pmu->setChargerConstantCurr(XPOWERS_AXP2101_CHG_CUR_500MA);
  pmu->disableIRQ(XPOWERS_AXP2101_ALL_IRQ);
  pmu->clearIrqStatus();
  pmu->disableTSPinMeasure();
  pmu->enableVbusVoltageMeasure();
  pmu->enableBattVoltageMeasure();

  if (out) {
    out->printf("PMU adapter: AXP2101 ready, BLDO1(SD)=%s\r\n",
                pmu->isPowerChannelEnable(XPOWERS_BLDO1) ? "ON" : "OFF");
  }

  return pmu->isPowerChannelEnable(XPOWERS_BLDO1);
}

} // namespace tbeam_supreme
