#ifndef VARIABLES_DATABASE_H
#define VARIABLES_DATABASE_H

#include <QObject>
#include <QThread>
#include <QQueue>
#include <QMutex>
#include <QMap>
#include <QDateTime>
#include <QElapsedTimer>
#include <QPolygonF>
#include <QSqlDatabase>
#include "history_database_base.h"

class SHSScriptProxy;
class SHSScriptEngine;


class SHSVariablesDatabase: public QThread {
	Q_OBJECT
	friend class SHSScriptProxy;
	friend class SHSScriptEngine;
public:
	explicit SHSVariablesDatabase(QObject * parent = 0);
	~SHSVariablesDatabase();
	
	void assignEngine(SHSScriptEngine * e, const QList<SHS::ScriptVariable> & in_vars);
	void start();
	void stop();
	bool isHistoryDBRunning() const;

	PIVector<PIPair<ullong, double>> getVariableHistory(const QString & vname);
	PIPair<ullong, double> getVariableValue(const QString & vname);

private:
	void run();
	double elapsedStartTM();
	void init();
	void setVarIdValue(QString vn, int id, double value);
	int variableID(const QString & name) const;
	double variableValue(int id) const;
	void setVariableValue(int id, double value);
	QVariant scriptVariableValue(int id) const;
	void setScriptVariableValue(int id, QVariant value);
	bool migrateOldHistory(QSqlDatabase & old_db);

	SHSScriptEngine * engine_ = nullptr;
	QList<SHSHistoryDatabaseBase *> history_dbs;
	QSqlDatabase db_vars;
	QMap<QString, int> vars_ids;
	QString db_filename;

	QMap<int, SHSHistoryDatabaseBase::Variable> vars;

	QMap<int, QVariant> script_vars;
	QMap<int, double> changed_vars;
	QQueue<QPair<int, QVariant>> db_script_queue;

	mutable QMutex db_mutex, tm_mutex;
	PITimeMeasurer start_tm;
	std::atomic_bool is_run, is_ready, is_migrating;
	
	void createHistoryDatabaseFromString(QString db, QString influx_addr);

private slots:
	void resetStartTM();
	void readVariablesHistory();
	
signals:
	
};

#endif // VARIABLES_DATABASE_H
