/*
 * 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/cgit/smolbote
 *
 * SPDX-License-Identifier: GPL-3.0
 */

#include "browser.h"
#include "cmd/cmd.hpp"
#include "configuration.h"
#include "util.h"
#include <QStandardPaths>
#include <spdlog/spdlog.h>

namespace builtins
{
int sub_configuration(const QStringList &l, Browser &);
int sub_bookmarks(const QStringList &l, Browser &);
int sub_session(const QStringList &l, Browser &);
}

int main(int argc, char **argv)
{
    // spdlog pattern
    if(const char *env_spdlog = std::getenv("POI_LOG_PATTERN")) {
        spdlog::set_pattern(env_spdlog);
    } else {
        spdlog::set_pattern("[%^%l%$] [%P:%t] %v");
    }

#ifdef QT_DEBUG
    spdlog::set_level(spdlog::level::debug); // Set global log level to debug
#endif

    const command_line::map<Browser> subcommands{
        { "configuration", builtins::sub_configuration },
        { "bookmarks", builtins::sub_bookmarks },
        { "session", builtins::sub_session },
    };

    // argc, argv, allowSecondary
    Browser app(argc, argv);
    // set this, otherwise the webview becomes black when using a stylesheet
    app.setAttribute(Qt::AA_DontCreateNativeWidgetSiblings, true);

    const auto f = command_line::process<Browser>(app, subcommands, "session");

    {
        // load plugins
        Configuration conf;
        const auto plugins_path = conf.value<QString>("plugins.path").value();
        for(const QString &path : Util::files(plugins_path, { "*.so", "*.dll" })) {
            app.loadPlugin(path) ? spdlog::debug("Loaded plugin [{}]", qUtf8Printable(path)) : spdlog::warn("Failed loading plugin [{}]", qUtf8Printable(path));
        }
    }

    return f(app);

}