#include "OpenDatabase.h"
#include "catalog/PgDatabaseCatalog.h"
#include "Pgsql_Connection.h"
#include "Pgsql_PgException.h"
#include "model/TypeSelectionItemModel.h"
#include <QDebug>

OpenDatabase::OpenDatabaseSPtr OpenDatabase::createOpenDatabase(const ConnectionConfig &cfg)
{
	try {
		OpenDatabaseSPtr odb(new OpenDatabase(cfg));
		odb->Init();
		return odb;
	}
    catch (const std::exception &ex) {
		throw OpenDatabaseException(ex.what());
	}
}

OpenDatabase::OpenDatabase(const ConnectionConfig& cfg)
	: m_config(cfg)
	, m_catalog(std::make_shared<PgDatabaseCatalog>())
{
}

OpenDatabase::~OpenDatabase() = default;

void OpenDatabase::Init()
{
	refresh();
}

std::shared_ptr<PgDatabaseCatalog> OpenDatabase::catalog()
{
	return m_catalog;
}


TypeSelectionItemModel* OpenDatabase::typeSelectionModel()
{
	if (m_typeSelectionModel == nullptr) {
		m_typeSelectionModel = new TypeSelectionItemModel(nullptr);
		m_typeSelectionModel->setTypeList(m_catalog->types());
	}
	return m_typeSelectionModel;
}

void OpenDatabase::refresh()
{
	Pgsql::Connection conn;
	auto connstr = m_config.connectionString();
	conn.connect(connstr);
	m_catalog->loadAll(conn, nullptr);
}
