#include "TriggerPage.h"
#include "ResultTableModelUtil.h"
#include "UserConfiguration.h"
#include "catalog/PgClass.h"
#include "widgets/SqlCodePreview.h"
#include "catalog/models/TriggerTableModel.h"
#include "CustomFilterSortModel.h"
#include "CustomDataRole.h"
#include "util/PgLabTableView.h"
#include "catalog/PgProcContainer.h"
#include <QHeaderView>
#include <QStringBuilder>
#include <unordered_set>

TriggerPage::TriggerPage(QWidget *parent)
	: CatalogPageBase(parent)
{
	m_model = new TriggerTableModel(this);
	m_sortFilterProxy->setSourceModel(m_model);

	connect(m_tableView->selectionModel(), &QItemSelectionModel::selectionChanged,
			this, &TriggerPage::tableView_selectionChanged);
	connect(m_model, &TriggerTableModel::modelReset, m_definitionView, &SqlCodePreview::clear);
}


void TriggerPage::catalogSet()
{
	m_model->setCatalog(m_catalog);
}


void TriggerPage::setFilter(const std::optional<PgClass> &cls)
{
	m_sortFilterProxy->setOidFilterTable(cls ? cls->oid() : InvalidOid, FirstHiddenValue);
	m_tableView->resizeColumnsToContents();
}


void TriggerPage::tableView_selectionChanged(const QItemSelection &/*selected*/, const QItemSelection &/*deselected*/)
{
	auto rijen = selectedRows();

	QString drops;
	QString creates;
	for (auto rij : rijen) {
		auto&& t = m_model->trigger(rij);
		drops += t.dropSql() % "\n";
		creates += t.createSql() % "\n";

		const PgProc *proc = m_catalog->procs()->getByKey(t.foid);
		if (proc) {
			creates += "\n" % proc->createSql() % "\n";
		}
	}
	m_definitionView->setPlainText(drops % "\n" % creates);
}
