#include "history_database_influxdb.h"
#include "influxdb.hpp"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>


SHSHistoryDatabaseInfluxDB::SHSHistoryDatabaseInfluxDB(const QString address): SHSHistoryDatabaseBase() {
	setObjectName("SHSHistoryDatabaseInfluxDB");
	QStringList sl = address.split(':');
	if (!sl.isEmpty()) {
		server_ip = sl.at(0).trimmed().toStdString();
		if (sl.size() > 1) {
			server_port = sl.at(1).toInt();
		} else {
			server_port = 8086;
		}
	} else {
		server_ip = "127.0.0.1";
		server_port = 8086;
	}
}


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


QPolygonF SHSHistoryDatabaseInfluxDB::readHistory(int id) {
	QPolygonF ret;
	influxdb_cpp::server_info si(server_ip, server_port, database_name, "", "", "ns");
	std::string resp;
	std::string vn = var_names.value(id, "var"+QString::number(id).toStdString());
	influxdb_cpp::query(resp, "select " + vn + " from "+ vn, si);
	QJsonDocument doc = QJsonDocument::fromJson(QString::fromStdString(resp).toUtf8());
	QJsonArray results = doc.object().value("results").toArray();
	if (!results.isEmpty()) {
		readHistoryTick();
		QJsonArray series = results.first().toObject().value("series").toArray();
		if (!series.isEmpty()) {
			QJsonArray values = series.first().toObject().value("values").toArray();
			for(auto v: values) {
				QJsonArray a = v.toArray();
				if (a.size() == 2) {
					ret << QPointF(a.at(0).toDouble(), a.at(1).toDouble());
				}
			}
		}
	}
//	qDebug() << "SHSHistoryDatabaseInfluxDB::readHistory" << QString::fromStdString(resp);
	return ret;
}


bool SHSHistoryDatabaseInfluxDB::init(QString filename, const QList<SHSHistoryDatabaseBase::Variable> & vars) {
	std::string resp;
	int ret;
	database_name = "SHS_"+filename.toStdString()+"_history";
	influxdb_cpp::server_info si(server_ip, server_port, database_name);
	ret = influxdb_cpp::create_db(resp, database_name, si);
	if (ret != 0) {
		qDebug() << "[SHSHistoryDatabaseInfluxDB] Error while open database" << QString::fromStdString(database_name);
		return false;
	}
	var_names.clear();
	for (auto v: vars) var_names.insert(v.id, v.name.toStdString());
	return true;
}


void SHSHistoryDatabaseInfluxDB::destroy() {
}


void SHSHistoryDatabaseInfluxDB::writeRows(int var_id, const QList<SHSHistoryDatabaseBase::HistoryRow> & rows) {
	if (rows.isEmpty()) return;
	influxdb_cpp::server_info si(server_ip, server_port, database_name, "", "", "ns");
	std::string vn = var_names.value(var_id, "var"+QString::number(var_id).toStdString());
	std::string q = influxdb_cpp::builder().meas(vn).field(vn, rows.first().value, 10).timestamp(rows.first().time).toString();
	for (int i=1; i<rows.size(); ++i) {
		q = influxdb_cpp::builder().append(q).meas(vn).field(vn, rows[i].value, 10).timestamp(rows[i].time).toString();
	}
	influxdb_cpp::builder().append(q).post_http(si);
}


void SHSHistoryDatabaseInfluxDB::removeOldRows(int var_id) {
}
