#include "catalog/widgets/CatalogConstraintPage.h"
#include "catalog/models/ConstraintModel.h"
#include "CustomFilterSortModel.h"
#include "catalog/delegates/IconColumnDelegate.h"
#include "util/PgLabTableView.h"
#include "widgets/SqlCodePreview.h"
#include <QHeaderView>
#include <QStringBuilder>

CatalogConstraintPage::CatalogConstraintPage(QWidget *parent)
	: CatalogPageBase(parent)
{
	m_constraintModel = new ConstraintModel(this);
	m_sortFilterProxy->setSourceModel(m_constraintModel);

	m_tableView->setItemDelegateForColumn(0, new IconColumnDelegate(this));
    m_tableView->horizontalHeader()->setSortIndicator(ConstraintModel::NameCol, Qt::AscendingOrder);
    m_tableView->setSortingEnabled(true);

	connect(m_tableView->selectionModel(), &QItemSelectionModel::selectionChanged,
			this, &CatalogConstraintPage::tableView_selectionChanged);
	connect(m_constraintModel, &ConstraintModel::modelReset, m_definitionView, &SqlCodePreview::clear);
}

void CatalogConstraintPage::catalogSet()
{
}

void CatalogConstraintPage::setFilter(const std::optional<PgClass> &cls)
{
	m_constraintModel->setData(m_catalog, cls);
	m_tableView->resizeColumnsToContents();
}

void CatalogConstraintPage::tableView_selectionChanged(const QItemSelection &/*selected*/, const QItemSelection &/*deselected*/)
{
    m_definitionView->setPlainText(
        generateSql(
            selectedRows()
        )
    );
}

QString CatalogConstraintPage::generateSql(const std::unordered_set<int> &rijen)
{
    QString drops;
    QString creates;
    for (auto rij : rijen) {
        const PgConstraint constraint = m_constraintModel->constraint(rij);
        drops += constraint.dropSql() % "\n";
        creates += constraint.createSql() % "\n";
    }
    return drops % "\n" % creates;
}
