#include "TestConnection.h"
#include "ConnectionConfig.h"
#include "Pgsql_Connection.h"
#include "Pgsql_PgException.h"

TestConnectionResult TestConnectionResult::Failed(QString msg)
{
    return TestConnectionResult(false, msg, {});
}

TestConnectionResult TestConnectionResult::Success(QStringList databases)
{
    return TestConnectionResult(true, "Test succesfull", databases);
}

bool TestConnectionResult::ok() const
{
    return Ok;
}

QString TestConnectionResult::message() const
{
    return Message;
}

const QStringList &TestConnectionResult::databases() const
{
    return Databases;
}

TestConnectionResult::TestConnectionResult(bool ok, QString msg, QStringList databases)
    : Ok(ok)
    , Message(msg)
    , Databases(databases)
{}

TestConnectionResult TestConnection(const ConnectionConfig &cc)
{
    try {
        Pgsql::Connection conn;
        conn.connect(cc.connectionString());

        auto result = conn.query(
            "SELECT datname\n"
            "  FROM pg_database\n"
            "  WHERE datallowconn AND has_database_privilege(datname, 'connect')\n"
            "  ORDER BY 1");

        QStringList dbs;
        for (auto row : result)
            dbs.append(row.get(0));

        return TestConnectionResult::Success(dbs);
    }
    catch (const Pgsql::PgException &ex) {
        return TestConnectionResult::Failed(QString::fromUtf8(ex.what()));
    }
}
