/* 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 "gpgolkeyadder-options.h"
#include "w32-gettext.h"
#include "w32-util.h"
#include "gpgolkeyadder.h"

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

#include <iostream>

#include <QApplication>
#include <QDebug>
#include <QTextCodec>
#include <QTimer>
#include <QMessageBox>

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

#ifndef APPNAME
#define APPNAME "GpgOL"
#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 */
    QApplication 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);

#ifdef Q_OS_WIN
    auto oldCodec = QTextCodec::codecForLocale();
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
#endif
    parser.process(app);
#ifdef Q_OS_WIN
    QTextCodec::setCodecForLocale(oldCodec);
#endif

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

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

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

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

    // Initialize w32-gettext
    const auto localeDir = W32::getGpg4winLocaleDir();
    if (!localeDir.empty()) {
        i18n_init("gpgol", localeDir.c_str());
    } else {
        qDebug() << "No locale dir.";
    }

    GpgOLKeyAdder mainWin(parser);
    mainWin.show();

    app.exec();

    return EXIT_SUCCESS;
}
