#include "TypeModel.h"
#include "catalog/PgDatabaseCatalog.h"
#include "catalog/PgNamespace.h"
#include "catalog/PgTypeContainer.h"

TypeModel::TypeModel(QObject * parent)
    : QAbstractTableModel(parent)
{
}

QVariant TypeModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal) {
        if (role == Qt::DisplayRole) {
            switch (section) {
            case NameCol: return tr("Name");
            case SchemaCol: return tr("Schema");
            case OwnerCol: return tr("Owner");
            }
        }
    }
    return {};
}

void TypeModel::setCatalog(std::shared_ptr<const PgDatabaseCatalog> cat)
{
    if (cat != m_catalog) {
        m_catalog = cat;
        refreshConnection = connect(m_catalog.get(), &PgDatabaseCatalog::refreshed,
                                        this, &TypeModel::refresh);
    }
    refresh();
}

//void TypeModel::setNamespaceFilter(NamespaceFilter filter)
//{
//    m_namespaceFilter = filter;
//    refresh();
//}

void TypeModel::refresh()
{
    if (!m_catalog)
        return;

    beginResetModel();

    auto && typs = m_catalog->types();
    m_types.clear();
    for (auto&& s : *typs) {
//        bool add = false;
//        switch (m_namespaceFilter) {
//        case NamespaceFilter::User:
//            add = !s.ns().isSystemCatalog();
//            break;
//        case NamespaceFilter::PgCatalog:
//            add = s.ns().objectName() == "pg_catalog";
//            break;
//        case NamespaceFilter::InformationSchema:
//            add = s.ns().objectName() == "information_schema";
//            break;
//        }
//        if (add)
        m_types.push_back(s);
    }

    endResetModel();
}

PgType TypeModel::typ(int row) const
{
    return m_types.at(static_cast<size_t>(row));
}

int TypeModel::rowCount(const QModelIndex &) const
{
    return static_cast<int>(m_types.size());
}

int TypeModel::columnCount(const QModelIndex &) const
{
    return colCount;
}

QVariant TypeModel::data(const QModelIndex &index, int role) const
{
    if (m_types.empty())
        return {};

    int row = index.row();
    auto && seq = m_types.at(static_cast<size_t>(row));
    if (role == Qt::DisplayRole) {
        switch (index.column()) {
        case NameCol: return seq.objectName();
        case SchemaCol: return seq.nsName();
        case OwnerCol: return seq.ownerName();
        }
    }

    return {};
}
