#include "PostgresqlUrlParser.h"

#include <ConnectionConfig.h>
#include <QUrl>
#include <QUrlQuery>

bool TryParsePostgresqlUrl(const QString &urlString, ConnectionConfig &out)
{
    const char* shortPrefix = "postgres";
    const char* longPrefix = "postgresql";

    auto url = QUrl(urlString, QUrl::StrictMode);
    if (url.scheme() != shortPrefix && url.scheme() != longPrefix)
        return false;

    out.setUser(url.userName());
    out.setPassword(url.password());
    out.setHost(url.host());
    out.setDbname(url.fileName());
    out.setPort(url.port(5432));

    QUrlQuery query(url.query());
    for (auto && param : query.queryItems())
    {
        if (param.first == "ssl" && param.second == "true") {
            out.setSslMode(SslMode::require);
        }
        else
        {
            out.setParameter(param.first, param.second);
        }
    }

    return true;
}

