#include "DatabasesPage.h"
#include "catalog/models/DatabasesTableModel.h"
#include "widgets/SqlCodePreview.h"
#include "SqlFormattingUtils.h"
#include "catalog/PgDatabaseCatalog.h"
#include "util/PgLabTableView.h"
#include <CreateDatabaseDialog.h>
#include <QAction>
#include <QStringBuilder>

DatabasesPage::DatabasesPage(std::shared_ptr<OpenDatabase> opendatabase, QWidget * parent)
    : QSplitter(Qt::Horizontal, parent)
    , m_databasesTableView(this, new DatabasesTableModel(opendatabase, this))
{
    auto tv = m_databasesTableView.itemView();
    tv->setSelectionMode(QAbstractItemView::SingleSelection);
    tv->setContextMenuPolicy(Qt::ActionsContextMenu);

    auto createDbAction = new QAction("Create database", this);
    tv->addAction(createDbAction);

    addWidget(tv);
    m_tableSql = new SqlCodePreview(this);
    addWidget(m_tableSql);

    connect(m_databasesTableView.itemView()->selectionModel(), &QItemSelectionModel::currentRowChanged,
            this, &DatabasesPage::databaseSelectionChanged);
    connect(createDbAction, &QAction::triggered,
            [this](auto checked)
            {
                auto dlg = new CreateDatabaseDialog(this->m_catalog, this);
                dlg->show();
            });
}

void DatabasesPage::setCatalog(std::shared_ptr<PgDatabaseCatalog> cat)
{
    m_catalog = cat;
    m_databasesTableView.dataModel()->setDatabaseList(cat);
    m_databasesTableView.itemView()->resizeColumnsToContents();
}

void DatabasesPage::updateDatabaseDetails(const PgDatabase &db)
{
    updateSqlTab(db);
}

void DatabasesPage::updateSqlTab(const PgDatabase &db)
{
    QString drop_sql = db.dropSql();
    QString create_sql = db.createSql();

    create_sql += "\n\n-- set Privileges\n";
    create_sql += db.grantSql() % "\n";

    create_sql += "-- set comment\n";
    create_sql += db.commentSql() % "\n";

    m_tableSql->setPlainText(drop_sql % "\n\n" % create_sql);
}

void DatabasesPage::databaseSelectionChanged(const QModelIndex &current, const QModelIndex &previous)
{
    if (current.row() == previous.row())
        return;

    auto db = m_databasesTableView.rowItemForProxyIndex(current);
    updateDatabaseDetails(db);
}






