#include <QFile>
#include <QTextStream>
#include <QCoreApplication>
#include "ProgressLog.h"
#include <QThread>
#include <QCoreApplication>
#include "version.h"
#include "LQError.h"
#include "PortLoader.h"
#include "protocol/dfu/stm32/BurnProtocolDfuSTM32.h"

static QTextStream &qstdout() {
    static QTextStream out{stdout, QIODevice::OpenModeFlag::WriteOnly};
    return out;
}

static QTextStream &qstderr() {
    static QTextStream out{stderr, QIODevice::OpenModeFlag::WriteOnly};
    return out;
}

class ConsoleLog : public ProgressLog {
public:
    void printDbg(const QString &msg, bool flush = true) override {
        qstdout() << msg;
        if (flush)
            qstdout().flush();
    }

    void printDbgLine(const QString &msg) override {
        printDbg(msg, false);
        printDbg(QStringLiteral("\n"), true);
    }
    void printProgress(qint64 done, qint64 total) override {
        Q_UNUSED(done) Q_UNUSED(total)

        printDbg(QStringLiteral("."), false);
    }
    void  printError(const QString &msg, const LQError &err)  override  {
        qstderr() << msg << QStringLiteral(" (") << QCoreApplication::tr("Error %1: %2").arg(err.errorCode()).arg(err.msg()) << QStringLiteral(")\n");
        qstderr().flush();
    }
};








int main(int argc, char **argv) {
    int ret = 0;

    QCoreApplication app{argc, argv};
    app.setApplicationName(QStringLiteral(PROJECT_APP_TITLE));
    app.setApplicationVersion(QStringLiteral(PROJECT_VERSION_STR));

    ConsoleLog log;
    LQError err;

    if (argc < 1) {

    } else {
        const QString fwName {QString::fromUtf8(argv[1])};

        BurnProtocolDfuSTM32 proto;
        PortLoader loader{};
        loader.init(proto, err, log);

        if (err.isSuccess()) {
            loader.cleanup(err, log);
        }

        if (err.isSuccess()) {
            loader.burn(fwName, err, log);
        }

        if (err.isSuccess()) {
            loader.startApp(err, log);
        }

    }

    return err.isSuccess() ? ret : err.errorCode();
}
