/* Copyright (C) 2018 by Intevation GmbH
 *
 * This file is free software under the GNU GPL (v>=2)
 * and comes with ABSOLUTELY NO WARRANTY!
 * See LICENSE.txt for details.
 */

/** @file Main entry point for the application.
 */
#include "strhelp.h"
#include "gpgcardgui.h"
#include <gpgme++/global.h>
#include <gpgme++/error.h>

#include <iostream>

#include <QDebug>
#include <QTimer>
#include <QMessageBox>
#include <QProcess>

#ifndef APPNAME
#define APPNAME "GpgCardGUI"
#endif

#ifndef VERSION
#define VERSION "0.0"
#endif

#include "gpgcardgui-options.h"

bool g_debug = false;

QtMessageHandler g_default_msg_handler = NULL;

void filterDebugOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    if (!g_debug && type == QtDebugMsg) {
        return;
    }

    if (g_default_msg_handler) {
        (*g_default_msg_handler)(type, context, msg);
    }
}

/** @brief The real entry point to the application.
 *
 * @param [in] argc the count of the arguments.
 * @param [in] argv On GNU/Linux this function expects argv to be in the
 * native system encoding. On Windows the arguments
 * shall be UTF-8
 *
 * @returns 0 on success an error code otherwise. */
int main(int argc, char **argv)
{
    /* QApplication setup */
    GpgCardGUI app(argc, argv);
    QApplication::setOrganizationName(QStringLiteral(APPNAME));
    QApplication::setApplicationName(QStringLiteral(APPNAME));
    QApplication::setApplicationVersion(QStringLiteral(VERSION));

    /* Parse the command line */
    QCommandLineParser parser;
    options(parser);
    parser.process (app);

    const auto lang = parser.value("lang");
    g_debug = parser.isSet("debug");
    g_default_msg_handler = qInstallMessageHandler(filterDebugOutput);

    if (!lang.isEmpty()) {
        qputenv("LANG", lang.toUtf8());
    }

    app.showWindow();

    /* Start the main event loop */
    return app.exec();
}
