#include "DependantsTableModel.h"
#include "catalog/PgDatabaseCatalog.h"
#include "catalog/PgConstraintContainer.h"
#include "catalog/PgClassContainer.h"


DependantsTableModel::DependantsTableModel(QObject *parent)
	: QAbstractTableModel(parent)
{
}

void DependantsTableModel::setCatalog(std::shared_ptr<const PgDatabaseCatalog> cat)
{
	if (cat != m_catalog) {
		m_catalog = cat;
		refreshConnection = connect(m_catalog.get(), &PgDatabaseCatalog::refreshed,
										this, &DependantsTableModel::refresh);
	}
	refresh();
}

void DependantsTableModel::loadForTable(Oid table_id)
{
	if (table_id != tableId) {
		tableId = table_id;
		refresh();
	}
}

QVariant DependantsTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
	if (orientation == Qt::Horizontal) {
		if (role == Qt::DisplayRole) {
			switch (section) {
			case NameCol: return tr("Table");
			case NamespaceCol: return tr("Namespace");
			}
		}
	}
	return {};
}

int DependantsTableModel::rowCount(const QModelIndex &) const
{
	return dependants.size();
}

int DependantsTableModel::columnCount(const QModelIndex &) const
{
	return colCount;
}

QVariant DependantsTableModel::data(const QModelIndex &index, int role) const
{
	if (role == Qt::DisplayRole) {
		auto&& data = dependants[index.row()];
		switch (index.column()) {
		case NameCol: return data.tableName;
		case NamespaceCol: return data.namespaceName;
		case ConstraintCol: return data.constraintName;
		}
	}
	return {};
}

void DependantsTableModel::refresh()
{
	if (!m_catalog)
		return;

	beginResetModel();
	dependants.clear();

	if (tableId != InvalidOid) {
		auto&& constraints = m_catalog->constraints();
		auto fkeys = constraints->getReferencedForRelation(tableId);

		dependants.reserve(static_cast<int>(fkeys.size()));
		auto&& tables = m_catalog->classes();
		for (auto&& fk : fkeys) {
			//dependants.append(
			auto t = tables->getByKey(fk.relid);
			if (t) {
				Item i;
				i.tableOid = t->oid();
				i.tableName = t->objectName();
				i.namespaceName = t->nsName();
				i.constraintName = fk.objectName();
				dependants.push_back(i);
			}
		}
	}
	endResetModel();
}
