#include "QueryParamListController.h"
#include "OpenDatabase.h"
#include "catalog/PgDatabaseCatalog.h"
#include "catalog/PgTypeContainer.h"
#include <QTableView>


QueryParamListController::QueryParamListController(QTableView *tv,
					std::shared_ptr<OpenDatabase> opendb, QWidget *parent)
	: QObject(parent)
	, paramTableView(tv)
	, m_openDatabase(opendb)
{
	if (opendb) {
		m_typeDelegate.setTypeSelectionModel(opendb->typeSelectionModel());
	}

	paramTableView->setModel(&m_paramList);
	paramTableView->setItemDelegateForColumn(1, &m_typeDelegate);
}

Pgsql::Params QueryParamListController::params() const
{
	Pgsql::Params params;
	auto types = m_openDatabase->catalog()->types();
	for (auto e : m_paramList.GetParams()) {
		// some types have two names that are in seperate fields
		// this function only checks one field currently :(
		// for example integer vs int4, bigint vs int8
		auto type = types->getByName(e.type);
		if (type) {
			Oid oid = type->oid();
			params.add(e.value, oid);
		}
		else
			throw std::runtime_error("missing type in parameter list");
	}
	return params;
}

bool QueryParamListController::empty() const
{

	return m_paramList.rowCount() == 0;
}

void QueryParamListController::on_addParam()
{
	m_paramList.insertRows(m_paramList.rowCount(), 1);
}

void QueryParamListController::on_removeParam()
{
	auto rc = m_paramList.rowCount();
	if (rc > 0)
		m_paramList.removeRows(rc-1, 1);
}
