#pragma once
#include <Arduino.h>

bool prepare_max17048()
{
    #if (USE_MAX17048 == 1)
        unsigned long max17048_begin_time = millis();
        #ifdef DEBUG
            lipo.enableDebugging();
            Serial.printf("[%s]: start USE_MAX17048\n",__func__);
        #endif
        if (! lipo.begin())
        {
            Serial.printf("[%s]: MAX17048 NOT detected ... Check your wiring or I2C ADDR!\n",__func__);
            // to avoid sleeping for 24h, undef USE_MAX17048 if broken
            return false;
        } else
        {
            // lipo.quickStart();     // not needed rather, MAX17048 can recalculate during the few consecutive measurements (althoug it takes many measurements to get it right or it is like it should be?)
            #ifdef DEBUG
                Serial.printf("[%s]: start MAX17048 OK\n",__func__);
            #endif
            // reset MAX17048 if NOT woke up from deep sleep and apply MAX17048_DELAY_ON_RESET_MS
            if (esp_reset_reason() != 8)
            {
            // #ifdef DEBUG
            // RESET is needed otherwise it will show 0V on first measurement and will go to sleep for 24h
                Serial.printf("[%s]: Resetting MAX17048 and applying delay for %dms\n",__func__,MAX17048_DELAY_ON_RESET_MS);
            // #endif
                lipo.reset();
                #ifdef MAX17048_DELAY_ON_RESET_MS
                    delay(MAX17048_DELAY_ON_RESET_MS);
                #else 
                    delay(200);
                #endif
            }
            return true;
        }
    #else
        #ifdef DEBUG
            Serial.printf("[%s]: DONT USE_MAX17048\n",__func__);
        #endif
        return false;
    #endif    
}


void get_battery(float *volts, uint8_t *prct)
{
    *volts = lipo.getVoltage();
    *prct = round(lipo.getSOC());
    if (*prct > 100) *prct = 100;
}