#include "HX711.h"
#include "SwimTrackerConfig.h"
#include <cstdint>

class Scale
{
public:
    bool measure(uint16_t &measurementOut)
    {
        long value = hx711_.read_average(CONFIG_MEASUREMENT_AVG_COUNT);
        LOG_TRACE("rv %ld\n", value);
        value -= offset_;
        
        if (value < 0)
            measurementOut = (int16_t)(-(value >> valueRightShift_ ));
        else
            measurementOut = 0;
        return true;
    }

    void begin(uint32_t pinDOUT, uint32_t pinSCK, int valueRightShift)
    {
        hx711_.begin(pinDOUT, pinSCK);
        valueRightShift_ = valueRightShift;
    };

    void tare(uint32_t numMeasurementsToAverage = 50)
    {
        auto v1 = hx711_.read_average(3);
        offset_ = hx711_.read_average(numMeasurementsToAverage);
        LOG_INFO("Init reading %ld, Tare offset %ld\n", v1, offset_);
    }

    const long &offset() const { return offset_; }
    int valueRightShift() const { return valueRightShift_; }
private:
    HX711 hx711_;
    long offset_ = 0;
    int valueRightShift_;
};
