#include "MasterController.h"
#include "ConnectionController.h"
#include "utils/PostgresqlUrlParser.h"
#include <ConnectionConfig.h>
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QStandardPaths>

namespace {

	QString GetUserConfigDatabaseName()
	{
		QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
		QDir dir(path);
		if (!dir.exists()) {
			dir.mkpath(".");
		}
		path += "/pglabuser.db";
		return path;
	}

}

MasterController::MasterController(QObject *parent) : QObject(parent)
{}

MasterController::~MasterController()
{}

void MasterController::init()
{
    m_userConfigDatabase.Open(GetUserConfigDatabaseName());

	m_connectionController = new ConnectionController(this);
    m_connectionController->init();


    QStringList arguments = QCoreApplication::arguments();
    for (auto && arg : arguments)
    {
        ConnectionConfig cfg;
        if (TryParsePostgresqlUrl(arg, cfg)) {
            m_connectionController->openSqlWindowForConnection(cfg);
            return;
        }
    }

    m_connectionController->showConnectionManager();
}

ConnectionController *MasterController::connectionController()
{
	return m_connectionController;
}

SQLiteConnection& MasterController::userConfigDatabase()
{
	return m_userConfigDatabase;
}


