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


CatalogIndexPage::CatalogIndexPage(QWidget *parent)
	: CatalogPageBase(parent)
{
	m_indexModel = new IndexModel(this);
	m_sortFilterProxy->setSourceModel(m_indexModel);
	m_tableView->setItemDelegateForColumn(0, new IconColumnDelegate(this));
    m_tableView->horizontalHeader()->setSortIndicator(IndexModel::NameCol, Qt::AscendingOrder);
    m_tableView->setSortingEnabled(true);

	connect(m_tableView->selectionModel(), &QItemSelectionModel::selectionChanged,
			this, &CatalogIndexPage::tableView_selectionChanged);
	connect(m_indexModel, &IndexModel::modelReset, m_definitionView, &SqlCodePreview::clear);
}

void CatalogIndexPage::catalogSet()
{
}

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

void CatalogIndexPage::tableView_selectionChanged(const QItemSelection &/*selected*/, const QItemSelection &/*deselected*/)
{
	auto rijen = selectedRows();
	QString drops;
	QString creates;
	for (auto rij : rijen) {
		const PgIndex index = m_indexModel->getIndex(rij);
		drops += index.dropSql() % "\n";
		creates += index.createSql() % "\n";
	}
	m_definitionView->setPlainText(drops % "\n" % creates);
}
