#include "esphome.h"
#include <MAX1704X.h>

class MAX1704xSensor : public PollingComponent, public sensor::Sensor {
 private:
  MAX1704X _fuelGauge1 = MAX1704X(5);

 public:
  sensor::Sensor *voltageSensor = new sensor::Sensor();
  sensor::Sensor *percentSensor = new sensor::Sensor();
  sensor::Sensor *isSleepingSensor = new sensor::Sensor();
  sensor::Sensor *alertIsActiveSensor = new sensor::Sensor();
  sensor::Sensor *getThresholdSensor = new sensor::Sensor();

  // 4294967295UL == never per sources
  MAX1704xSensor() : PollingComponent(60*60*1000) { }

  void setup() override {
       _fuelGauge1.begin();
       _fuelGauge1.reset();
       _fuelGauge1.quickstart();
  }

  void update() override {
    _fuelGauge1.wake();
    sleep(10);
    float voltage = _fuelGauge1.voltage();
    float percent = _fuelGauge1.percent();
    bool isSleeping = _fuelGauge1.isSleeping();
    bool alertIsActive = _fuelGauge1.alertIsActive();
    uint8_t getThreshold = _fuelGauge1.getThreshold();

    voltageSensor->publish_state(voltage);
    percentSensor->publish_state(percent);
    isSleepingSensor->publish_state(isSleeping);
    alertIsActiveSensor->publish_state(alertIsActive);
    getThresholdSensor->publish_state(getThreshold);
    _fuelGauge1.sleep();
  }
};
