#include "RolesTableModel.h"
#include "catalog/PgAuthIdContainer.h"

RolesTableModel::RolesTableModel(QObject *parent)
	: BaseTableModel(parent)
{
}

void RolesTableModel::setRoleList(std::shared_ptr<const PgAuthIdContainer> roles)
{
	beginResetModel();
	m_roles = roles;
	endResetModel();
}

QVariant RolesTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
	QVariant v;
	if (orientation == Qt::Horizontal) {
		if (role == Qt::DisplayRole) {
			switch (section) {
			case NameCol:
				v = tr("Name");
				break;
			case SuperCol:
				v = tr("Super");
				break;
			case InheritCol:
				v = tr("Inherit");
				break;
			case CreateRoleCol:
				v = tr("Create role");
				break;
			case CreateDBCol:
				v = tr("Create DB");
				break;
			case CanLoginCol:
				v = tr("Can login");
				break;
			case ReplicationCol:
				v = tr("Replication");
				break;
			case BypassRlsCol:
				v = tr("Bypass RLS");
				break;
			case ConnlimitCol:
				v = tr("Connection limit");
				break;
			case ValidUntilCol:
				v = tr("Valid until");
				break;
			}
		}
	}

	return v;
}

int RolesTableModel::rowCount(const QModelIndex &/*parent*/) const
{
	int result = 0;
	if (m_roles) {
		result = m_roles->count();
	}
	return result;
}

int RolesTableModel::columnCount(const QModelIndex &/*parent*/) const
{
	int result = 10;
//	if (parent.isValid())
//		return 10;

	return result;
}

Oid RolesTableModel::getType(int column) const
{
	using namespace Pgsql;

	Oid oid;
	switch (column) {
	case NameCol:
		oid = varchar_oid;
		break;

	case ReplicationCol:
	case BypassRlsCol:
	case CanLoginCol:
	case CreateDBCol:
	case CreateRoleCol:
	case InheritCol:
	case SuperCol:
		oid = bool_oid;
		break;

	case ConnlimitCol:
		oid = int4_oid;
		break;

	case ValidUntilCol:
		oid = timestamp_oid;
		break;
	default:
		oid = InvalidOid;
	}

	return oid;
}

QVariant RolesTableModel::getData(const QModelIndex &index) const
{
	QVariant v;
	if (m_roles) {
		const PgAuthId &authid = m_roles->getByIdx(index.row());
		switch (index.column()) {
		case NameCol:
			v = authid.objectName();
			break;
		case SuperCol:
			// todo lookup role name
			v = authid.super;
			break;
		case InheritCol:
			// todo lookup encoding name
			v = authid.inherit;
			break;
		case CreateRoleCol:
			v = authid.createRole;
			break;
		case CreateDBCol:
			v = authid.createDB;
			break;
		case CanLoginCol:
			v = authid.canlogin;
			break;
		case ReplicationCol:
			v = authid.replication;
			break;
		case BypassRlsCol:
			v = authid.bypassRls;
			break;
		case ConnlimitCol:
			v = authid.connLimit;
			break;
		case ValidUntilCol:
			v = authid.validUntil;
			break;
		}
	}
	return v;
}
