#include "mainwindow.h"
#include "application.h"
#include <QCommandLineParser>
#include <QSettings>
#include <QSurfaceFormat>
#include <QTranslator>
#include <stdlib.h>
#include "../thumbnailer/genthumbnail.h"
#ifdef Q_OS_WIN64
#include <windows.h>
#endif

bool DEBUG_LOG = false;

QtMessageHandler defaultHandler = nullptr;

void messageHandler(QtMsgType type, const QMessageLogContext &ctx, const QString &message)
{
    if(defaultHandler)
    {
        if(DEBUG_LOG || type != QtMsgType::QtDebugMsg)
            defaultHandler(type, ctx, message);
    }
}

int main(int argc, char *argv[])
{
#ifdef __linux__
    setenv("LC_NUMERIC", "C", 1);
#endif

#if defined(__i386__) || defined(__x86_64__) || defined(__APPLE__)
    bool useGLES = false;
#else
    bool useGLES = true;
#endif

#ifdef Q_OS_WIN64
    if(AttachConsole(ATTACH_PARENT_PROCESS))
    {
        freopen("CONOUT$", "w", stdout);
        freopen("CONOUT$", "w", stderr);
    }
#endif
    defaultHandler = qInstallMessageHandler(messageHandler);

    QCommandLineParser cmd;
    cmd.addOption({"gl", "Use desktop OpenGL. This is default on x86 and MacOS platform."});
    cmd.addOption({"gles", "Use OpenGL ES. This is default on ARM platform."});
    cmd.addOption({{"thumb", "thumbnail"}, "Generate thumbnail and save it to path.", "path"});
    cmd.addOption({{"s", "size"}, "Size of the thumbnails in pixels (default: 128)", "size", "128"});
    cmd.addPositionalArgument("file", "Files or paths to open");
    cmd.addOption({"script", "Execute script", "script"});
    cmd.addOption({"scriptarg", "String that will be passed to script as variable \"scriparg\"", "arg"});
    cmd.addOption({"outdir", "Output dir for script (default: CWD)", "dir", "."});
    cmd.addOption({"noexit", "Do not exit application when script finish"});
    cmd.addOption({"debug", "Print debug info"});
    cmd.addHelpOption();
    QStringList cmdArgs;
    for(int i = 0; i < argc; i++)
        cmdArgs.append(argv[i]);

    cmd.process(cmdArgs);
    if(cmd.isSet("gl"))
        useGLES = false;
    if(cmd.isSet("gles"))
        useGLES = true;

    if(cmd.isSet("debug"))
        DEBUG_LOG = true;

    if(cmd.isSet("thumb"))
    {
        QCoreApplication app(argc, argv);
        QStringList files = cmd.positionalArguments();
        if(files.size() == 0)
            return 1;

        QString thumb = cmd.value("thumb");
        int size = 128;
        bool ok;
        int size2 = cmd.value("s").toInt(&ok);
        if(ok)
            size = size2;

        return generateThumbnail(files.front(), thumb, size);
    }

    QSurfaceFormat format;
    if(useGLES)
    {
        format.setMajorVersion(3);
        format.setMinorVersion(0);
        format.setRenderableType(QSurfaceFormat::OpenGLES);
    }
    else
    {
        format.setMajorVersion(3);
        format.setMinorVersion(3);
        //format.setOption(QSurfaceFormat::DebugContext);
        format.setProfile(QSurfaceFormat::OpenGLContextProfile::CoreProfile);
    }
    QSurfaceFormat::setDefaultFormat(format);

    Application a(argc, argv);
    a.setOrganizationName("nou");
    a.setApplicationName("Tenmon");
    a.setWindowIcon(QIcon(":/space.nouspiro.tenmon_64.png"));

    QTranslator translator;
    QTranslator translator2;
    QSettings settings;
    QString lang = settings.value("settings/lang").toString();
    if(lang.isEmpty())
    {
        if(translator.load(QLocale(), "tenmon", "_", ":/translations"))
            a.installTranslator(&translator);
    }
    else
    {
        if(translator.load("tenmon_" + lang, ":/translations"))
            a.installTranslator(&translator);
    }

    if(translator2.load(QLocale(), "tenmon", "_", a.applicationDirPath()))
        a.installTranslator(&translator2);

    MainWindow w;
    QObject::connect(&a, &Application::openFileEvent, &w, static_cast<void (MainWindow::*)(const QString&)>(&MainWindow::loadFile));
    w.show();

    if(!cmd.positionalArguments().isEmpty() && !cmd.isSet("script"))
    {
        QStringList files = cmd.positionalArguments();
        QStringList paths;
        for(auto &arg : files)
        {
            QUrl url(arg);
            QFileInfo info(url.isLocalFile() ? url.toLocalFile() : arg);
            if(info.exists())
                paths.append(info.canonicalFilePath());
        }
        if(paths.size() == 1)
            w.loadFile(paths.front());
        else if(paths.size() > 1)
            w.loadFiles(paths);
    }

    if(cmd.isSet("script"))
    {
        QStringList paths = cmd.positionalArguments();
        QString script = cmd.value("script");
        QString outdir = cmd.value("outdir");
        QString arg = cmd.value("scriptarg");
        if(!QDir::isAbsolutePath(script))script = QDir::currentPath() + "/" + script;
        if(!QDir::isAbsolutePath(outdir))outdir = QDir::currentPath() + "/" + outdir;
        bool noexit = cmd.isSet("noexit");
        if(!noexit)w.hide();
        w.runScript(script, outdir, paths, arg, !noexit);
    }

    return a.exec();
}
