#ifndef HISTORY_DATABASE_BASE_H
#define HISTORY_DATABASE_BASE_H

#include <QObject>
#include <QThread>
#include <QMutex>
#include <QMap>
#include <QPolygonF>
#include "SH_types.h"


class SHSHistoryDatabaseBase: public QThread {
	Q_OBJECT
public:
	explicit SHSHistoryDatabaseBase();
	virtual ~SHSHistoryDatabaseBase();

	struct Variable {
		Variable() {id = 0; value = 0.; duration = 0;}
		int id;
		double value;
		quint64 duration;
		QString name;
		QPolygonF history;
	};

	void start(QString filename);
	void stop();
	void setVariables(const QList<SHSHistoryDatabaseBase::Variable> & vars);
	void add(int id, qint64 t, double value);
	bool isRunning() const {return is_run;}

	virtual QPolygonF readHistory(int id) = 0;

protected:
	struct HistoryRow {
		int id = -1;
		double value = 0.;
		qint64 time;
	};

	void setStartTimeout(double sec) {start_timeout = sec;}
	void setStopTimeout (double sec) {stop_timeout = sec;}
	void setCleanTimeout(double sec) {clean_timeout = sec;}
	void readHistoryTick();

	virtual bool init(QString filename, const QList<SHSHistoryDatabaseBase::Variable> & vars) = 0;
	virtual void destroy() = 0;
	virtual void writeRows(int var_id, const QList<HistoryRow> & rows) = 0;
	virtual void removeOldRows(int var_id) = 0;
	virtual void transaction() {}
	virtual void commit() {}

	QMap<int, SHSHistoryDatabaseBase::Variable> var_by_id;

private:
	void resetStartTM();
	double elapsedStartTM();
	void run();

	QList<SHSHistoryDatabaseBase::Variable> init_vars;
	PIMap<int, QList<HistoryRow>> add_queue;
	QMutex add_mutex, tm_mutex;
	PITimeMeasurer start_tm;
	QString db_filename;
	std::atomic_bool is_run, is_ready;
	double start_timeout = 60., stop_timeout = 10., clean_timeout = 10.;
	
private slots:
	
signals:
	void readHistoryRequest();
	void readHistoryProgress();
	
};

#endif
