#include "QueryResultModel.h"
#include "ResultTableModelUtil.h"
#include "Pgsql_declare.h"
#include "Pgsql_oids.h"
#include "catalog/PgDatabaseCatalog.h"
#include "CustomDataRole.h"
#include <QBrush>
#include <QColor>

using namespace Pgsql;

QueryResultModel::QueryResultModel(QObject *parent, std::shared_ptr<Pgsql::Result> r
			, std::shared_ptr<PgDatabaseCatalog> cat)
	: QAbstractTableModel(parent)
	, result(std::move(r))
	, catalog(cat)
{}


int QueryResultModel::rowCount(const QModelIndex &) const
{
	int r = result->rows();
	return r;
}

int QueryResultModel::columnCount(const QModelIndex &) const
{
	int r = result->cols();
	return r;
}

QVariant QueryResultModel::data(const QModelIndex &index, int role) const
{
//	static const QString null_str("null");
	QVariant v;

	const int col = index.column();
	const int rij = index.row();
	const Oid oid = result->type(col);
	if (role == Qt::DisplayRole || role == Qt::EditRole) {
		if (result->null(col, rij)) {
			//v = nullptr;
		}
		else {
			Value value = result->get(col, rij);
			if (oid == bool_oid) {
				bool b = value;
				v = b;
			}
			else {
				QString s = value;
				v = s;
			}
		}
	}
    else if (role == CustomDataTypeRole) {
		v = oid;
	}


	return v;
}

QVariant QueryResultModel::headerData(int section, Qt::Orientation orientation, int role) const
{
	QVariant r;
	if (role == Qt::DisplayRole) {
		if (orientation == Qt::Horizontal) {
			QString s(result->getColName(section));
			s += "\n";
			s += getTypeDisplayString(*catalog, result->type(section));
			r = s;
		}
		else {
			r = QString::number(section + 1);
		}
	}
	Qt::ItemFlags f;
	return r;
}

Qt::ItemFlags QueryResultModel::flags(const QModelIndex &) const
{
	return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable;
}
