#include <cmath>
#include <SPIFFS.h>

class DataLogger
{
public:
	struct Entry
	{
		float batteryVoltage = 0.0f; // V
		float batteryOutputCurrent = 0.0f; // A
		float speed = 0.0f; // m/s
		float temperature = 0.0f; // in °C
		float altitude = 0.0f; // in m

		bool isDifferent(const Entry& other)
		{
			const float scale = speed > 0.0f || other.speed > 0.0f ? 1.0f : 5.0f;
			return
				   std::abs(batteryVoltage - other.batteryVoltage) > 0.1f * scale
				|| std::abs(batteryOutputCurrent - other.batteryOutputCurrent) > 0.1f * scale
				|| std::abs(speed - other.speed) > 0.1f
				|| std::abs(temperature - other.temperature) > 0.5f * scale
				|| std::abs(altitude - other.altitude) > 0.5f * scale;
		}
	};

public:
	DataLogger();
	~DataLogger();

	static DataLogger& get() { return mainLogger; }

	void open();
	void close();
	void log(unsigned long timeMilliseconds, const Entry& entry);

	bool isOpen();
	const char* currentLogFileName();

private:
	static DataLogger mainLogger;

	Entry lastEntry;
	unsigned long lastTimeMilliseconds = -1;
	float currentTime = 0.0f;
	float lastLogTime = 0.0f;
	float lastFlushTime = 0.0f;

	File file; // @suppress("Abstract class cannot be instantiated")
};
