#include "mainwindow.h"
#include <QApplication>
#include <QtGlobal>
#include <QtDebug>
#include <QTextStream>
#include <QTextCodec>
#include <QLocale>
#include <QTime>
#include <QFile>

#include "bsk_versign.h"

BSK_VERSIGN_STD_DEFINE("FpgaBeamMeUp", BSK_VERSIGN_STR_VER3(1, 0, 0), "N/A", "FpgaBeamMeUp", "GCC " __VERSION__);

const QString logFilePath = "debug.log";
bool logToFile = false;

// cross-platform solution to log to the console if app was ran from Qt Creator, and
// to the debug.log file, when it is compiled and being ran as a standalone app.
void customMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QHash<QtMsgType, QString> msgLevelHash({{QtDebugMsg, "Debug"}, {QtInfoMsg, "Info"}, {QtWarningMsg, "Warning"}, {QtCriticalMsg, "Critical"}, {QtFatalMsg, "Fatal"}});
    QByteArray localMsg = msg.toLocal8Bit();
    QTime time = QTime::currentTime();
    QString formattedTime = time.toString("hh:mm:ss.zzz");
    QByteArray formattedTimeMsg = formattedTime.toLocal8Bit();
    QString logLevelName = msgLevelHash[type];
    QByteArray logLevelMsg = logLevelName.toLocal8Bit();

    if (logToFile) {
        QString txt = QString("%1 %2: %3 (%4)").arg(formattedTime, logLevelName, msg,  context.file);
        QFile outFile(logFilePath);
        outFile.open(QIODevice::WriteOnly | QIODevice::Append);
        QTextStream ts(&outFile);
        ts << txt << endl;
        outFile.close();
    } else {
        //fprintf(stdout, "%s %s: %s (%s:%u, %s)\n", formattedTimeMsg.constData(), logLevelMsg.constData(), localMsg.constData(), context.file, context.line, context.function);
        fprintf(stdout, "%s %s: %s\n", formattedTimeMsg.constData(), logLevelMsg.constData(), localMsg.constData());
        fflush(stdout);
    }

    if (type == QtFatalMsg)
        abort();
}

int main(int argc, char *argv[])
{

   /* QByteArray envVar = qgetenv("QTDIR");       //  check if the app is ran in Qt Creator

    if (envVar.isEmpty())
        logToFile = true;

    qInstallMessageHandler(customMessageOutput); // custom message handler for debugging
*/

    QApplication a(argc, argv);

    QString appNameVer=
            QString("%1 (%2-%3)")
                .arg("FpgaBeamMeUp")
                .arg(versign_application_signature_.data.vstr)
                .arg(versign_application_ext_signature_.data.buildid);

    a.setApplicationDisplayName(appNameVer);

    MainWindow w;
    w.show();

    return a.exec();
}
