#include "sql_query.h"

#include <QDebug>


QAD::SQLQuery::SQLQuery(QString query_, QVariantMap params, QSqlDatabase db): q(db) {
	QMapIterator<QString, QVariant> it(params);
	while (it.hasNext()) {
		it.next();
		query_.replace("${" + it.key() + "}", it.value().toString());
	}
	q.prepare(query_);
	it.toFront();
	while (it.hasNext()) {
		it.next();
		q.bindValue(":" + it.key(), it.value());
	}
}


QAD::SQLQuery::~SQLQuery() {}


QAD::SQLQuery::Result QAD::SQLQuery::exec(QString query_, QVariantMap params, QSqlDatabase db) {
	QAD::SQLQuery::Result ret;
	QAD::SQLQuery q(query_, params, db);
	// qDebug() << query_ << params;
	if (q.q.exec()) {
		ret.ok       = true;
		ret.rows     = q.q.numRowsAffected();
		ret.insertId = q.q.lastInsertId();
		ret.query    = q.q;
		return ret;
	}
	if (Singleton::instance()->fail_handler) Singleton::instance()->fail_handler(q.q.lastQuery(), params, q.q.lastError());
	return ret;
}


QAD::SQLQuery::Result QAD::SQLQuery::insert(QString table, QVariantMap values, QSqlDatabase db) {
	QVariantMap params;
	QString qi = "INSERT INTO " + table + " (", qp, ph;
	QMapIterator<QString, QVariant> it(values);
	while (it.hasNext()) {
		it.next();
		ph = "v" + it.key();
		qi += it.key();
		qp += ":" + ph;
		params[ph] = it.value();
		if (it.hasNext()) {
			qi += ",";
			qp += ",";
		}
	}
	return exec(qi + ") VALUES (" + qp + ")", params, db);
}


QAD::SQLQuery::Result QAD::SQLQuery::remove(QString table, QString filter, QSqlDatabase db) {
	QString flt;
	if (!filter.isEmpty()) flt = " WHERE ";
	return exec("DELETE FROM " + table + flt + filter, {}, db);
}


bool QAD::SQLQuery::drop(QString table, QSqlDatabase db) {
	return exec("DROP TABLE " + table, {}, db).ok;
}


void QAD::SQLQuery::setFailHandler(QAD::SQLQuery::HandlerFail h) {
	Singleton::instance()->fail_handler = h;
}


QAD::SQLQuery::Singleton * QAD::SQLQuery::Singleton::instance() {
	static QAD::SQLQuery::Singleton ret;
	return &ret;
}
