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

#include "quitter.h"
#include "util/overlay.h"

#include <iostream>

#include <QDebug>
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
#include <QTextCodec>
#endif
#include <QTimer>
#include <QMessageBox>
#include <QApplication>

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

#ifndef APPNAME
#define APPNAME "Overlayer"
#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
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    auto oldCodec = QTextCodec::codecForLocale();
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
#endif
#endif
    parser.process(app);
#ifdef Q_OS_WIN
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    QTextCodec::setCodecForLocale(oldCodec);
#endif
#endif

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

    // Start quitter in the event loop
    QTimer::singleShot(0, [&parser, &app]() {
        Quitter *quitter = new Quitter;
        quitter->start();
    });
    Overlay *overlay;

    const auto hwnd = parser.value(QStringLiteral("hwnd"));
    if (!hwnd.isEmpty()) {
        bool ok;
        WId id = (WId) hwnd.toInt(&ok);
        if (!ok) {
            std::cerr << "invalid hwnd value" << std::endl;
            return EXIT_FAILURE;
        }
        overlay = new Overlay(id, parser.value(QStringLiteral("overlayText")));
    } else {
        std::cerr << "no hwnd value" << std::endl;
        return EXIT_FAILURE;
    }

    return app.exec();
}
