/*
 * This file is part of smolbote. It's copyrighted by the contributors recorded
 * in the version control history of the file, available from its original
 * location: https://neueland.iserlohn-fortress.net/smolbote.hg
 *
 * SPDX-License-Identifier: GPL-3.0
 */

#include "browser.h"
#include "mainwindow/mainwindow.h"
#include "version.h"
#include "webengine/webprofile.h"
#include <configuration/configuration.h>
#include <memory>

int main(int argc, char **argv)
{
    Browser app(argc, argv);

    // create and load configuration
    std::shared_ptr<Configuration> config = std::make_shared<Configuration>();
    if(!config->parseCommandLine(argc, argv)) {
        qWarning("Check --help for usage.");
        return -1;
    }
    if(!config->parseConfigFile(config->value<std::string>("config").value())) {
        qWarning("Error parsing config file.");
    }

    app.setConfiguration(config);

    // set up socket
    bool isSingleInstance = app.bindLocalSocket(QString::fromStdString(config->value<std::string>("socket").value()));
#ifdef QT_DEBUG
    qDebug("bindLocalSocket(%s) = %s", qUtf8Printable(QString::fromStdString(config->value<std::string>("socket").value())), isSingleInstance ? "true" : "false");
#endif

    // if we are the only instance, set up the browser
    if(isSingleInstance) {
        app.setup(QString::fromStdString(config->value<std::string>("profile.default").value()));
        QObject::connect(&app, &Browser::messageAvailable, &app, &Browser::createSession);
    }

    app.sendMessage("", false, config->positionalArguments());

    if(isSingleInstance)
        return app.exec();
    else
        return 0;
}