/* 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 "resolver-options.h"

#include "resolver.h"

#include <gpgme++/global.h>
#include <gpgme++/error.h>

#include <iostream>

#include <QDebug>

#include <QTimer>
#include <QMessageBox>

#ifdef Q_OS_WIN
 #include <windows.h>
 #include <shlobj.h>
#endif

#ifndef APPNAME
#define APPNAME "Resolver"
#endif

#ifndef VERSION
#define VERSION "0.0"
#endif

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);
    }
}

int realMain(int argc, char **argv);

#if defined(WIN32) && defined(UNICODE)

/** @brief Unicode entry point.
 *
 * Converts arguments to UTF-8 and executes the real
 * entry point realMain.
 */
int wmain(int argc, wchar_t **argv, wchar_t **envp)
{
    char **utf8args = NULL;

    utf8args = (char**) xmalloc0 ((argc + 1) * sizeof(char*));

    for (int i = 0; i < argc; i++) {
        utf8args[i] = wchar_to_utf8(argv[i], wcslen(argv[i]));
        if (utf8args[i] == NULL) {
            printf ("Fatal: could not convert arguments to UTF-8.\n");
            exit(-1);
        }
    }
    int ret = realMain(argc, utf8args);
    strv_free(utf8args);

    return ret;
}
#else
int main(int argc, char **argv)
{
    return realMain(argc, argv);
}
#endif

/** @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 realMain(int argc, char **argv)
{
    /* QApplication setup */
    Resolver app(argc, argv);
    QApplication::setOrganizationName(QStringLiteral(APPNAME));
    QApplication::setApplicationName(QStringLiteral(APPNAME));
    QApplication::setApplicationVersion(QStringLiteral(VERSION));

#if 0
    /* Setup translations */
    QTranslator translator;
    if (QLocale::system().name() == "C") {
        /* Useful for testing / development as the primary target is german */
        translator.load(":/l10n/main_de_DE");
    } else {
        translator.load(":/l10n/main_" + QLocale::system().name());
    }
    app.installTranslator(&translator);
#endif

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

    parser.process(app);

    g_debug = parser.isSet("debug");
    g_default_msg_handler = qInstallMessageHandler(filterDebugOutput);

    // Initialize GpgME
    const GpgME::Error gpgmeInitError = GpgME::initializeLibrary(0);

    if (gpgmeInitError) {
        QMessageBox::critical(nullptr, QObject::tr("Installation Error"),
                QObject::tr("Could not initialize GPGME.") + "<br/>" +
                QObject::tr("Please reinstall") + " " APPNAME ".");
        return EXIT_FAILURE;
    }

    const auto lang = parser.value("lang");

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

    // Go with the app
    QTimer::singleShot(0, [&parser, &app]() {
        const QString err = app.newInstance(parser);
        if (!err.isEmpty()) {
            std::cerr << QObject::tr("Invalid arguments: %1").arg(err).toLocal8Bit().constData() << "\n";
            exit(EXIT_FAILURE);
        }
    });
    app.exec();

    return EXIT_SUCCESS;
}
