#include "history_database_sqlite.h"
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlError>


SHSHistoryDatabaseSQLite::SHSHistoryDatabaseSQLite(): SHSHistoryDatabaseBase() {
	setObjectName("SHSHistoryDatabaseSQLite");
}


SHSHistoryDatabaseSQLite::~SHSHistoryDatabaseSQLite() {
	stop();
}


QPolygonF SHSHistoryDatabaseSQLite::readHistory(int id) {
	QPolygonF ret;
	QSqlQuery q(db);
	if (!q.exec(QString("SELECT * FROM var%1").arg(id))) {
		qDebug() << q.lastError();
		return ret;
	}
	ret.reserve(q.size());
	while (q.next()) {
		ret << QPointF(q.value(0).toDouble(), q.value(1).toDouble());
	}
	readHistoryTick();
	//qDebug() << "readHistory" << id << "read" << ret.size();
	return ret;
}


bool SHSHistoryDatabaseSQLite::init(QString filename, const QList<Variable> & vars) {
	db = QSqlDatabase::addDatabase("QSQLITE", "HistoryDB");
	db.setDatabaseName("projects/" + filename + "_history.dat");
	if (!db.open()) {
		qDebug() << "[SHSHistoryDatabaseSQLite] Error while open database" << db.databaseName();
		return false;
	}
	QSqlQuery q(db);
	db.transaction();
	for (const auto & v: vars) {
		q.exec(QString("CREATE TABLE var%1 (time integer(8) primary key, value real)").arg(v.id));
	}
	db.commit();
	return true;
}


void SHSHistoryDatabaseSQLite::destroy() {
	db.close();
	db = QSqlDatabase();
	QSqlDatabase::removeDatabase("HistoryDB");
}


void SHSHistoryDatabaseSQLite::writeRows(int var_id, const QList<HistoryRow> & rows) {
	//qDebug() << "writeRows" << var_id << rows.size();
	QSqlQuery q(db);
	for (const auto & r: rows) {
		q.prepare(QString("INSERT INTO var%1 (time,value) VALUES (:t,:v)").arg(var_id));
		q.bindValue(":t", r.time);
		q.bindValue(":v", r.value);
		q.exec();
	}
}


void SHSHistoryDatabaseSQLite::removeOldRows(int var_id) {
	qint64 vardur = var_by_id[var_id].duration;
	//qDebug() << "removeOldRows" << var_id;
	if (vardur == 0) return;
	qint64 cdt = QDateTime::currentMSecsSinceEpoch();
	QSqlQuery q(db);
	q.prepare(QString("DELETE FROM var%1 WHERE time<:t").arg(var_id));
	q.bindValue(":t", cdt - vardur);
	if (!q.exec()) {
		qDebug() << q.lastError();
	}
}


void SHSHistoryDatabaseSQLite::transaction() {
	db.transaction();
}


void SHSHistoryDatabaseSQLite::commit() {
	db.commit();
}
