#include <QtGlobal>
#include <QCoreApplication>
#include <QByteArray>

#include <QProcess>
#include <QCommandLineParser>
#include <QStandardPaths>
#include <QSettings>
#include <QDir>
#include <QDebug>

#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QRegularExpression>
#include <QFile>
#include <QTextStream>
#include <QRegularExpression>

#include <optional>

#include "message_handler.h"
#include "utils_internal.h"
#include "git_command.h"

int main(int argc, char **argv) {
    QByteArray const value = qgetenv("LC_ALL");
    if (value.isEmpty() || value != "C") {
        qputenv("LC_ALL", "C");
    }

    openlog("ATB-UPDATE-GIT", LOG_PERROR | LOG_PID | LOG_CONS, LOG_USER);

    QCoreApplication a(argc, argv);
    QCoreApplication::setApplicationName("ATBUpdateGit");
    QCoreApplication::setApplicationVersion(APP_VERSION);

    if (!messageHandlerInstalled()) { // change internal qt-QDebug-handling
        atbInstallMessageHandler(nullptr);
        //atbInstallMessageHandler(atbDebugOutput);
        setDebugLevel(LOG_NOTICE);
    }

    QCommandLineParser parser;
    parser.setApplicationDescription("git-commands for the update-system");

    QCommandLineOption const checkCustomerRepositoryOption{"check"};
    QCommandLineOption const cloneCustomerRepositoryOption{"clone"};
    QCommandLineOption const pullBranchOption{"pull"};
    QCommandLineOption const checkoutBranchOption("checkout");

    parser.addOption(checkCustomerRepositoryOption);
    parser.addOption(cloneCustomerRepositoryOption);
    parser.addOption(pullBranchOption);
    parser.addOption(checkoutBranchOption);

    QCommandLineOption verboseOption{parser.addVersionOption()};
    parser.process(a);

    if (parser.isSet(verboseOption)) {
        parser.showVersion();
        return 0;
    }

    GitCommand gitCmd;

    if (parser.isSet(checkCustomerRepositoryOption)) {
        if (!gitCmd.check()) {
            return -1;
        }
    } else
    if (parser.isSet(checkoutBranchOption)) {
        if (!gitCmd.checkout()) {
            return -2;
        }
    } else
    if (parser.isSet(cloneCustomerRepositoryOption)) {
        if (!gitCmd.clone()) {
            return -3;
        }
    } else
    if (parser.isSet(pullBranchOption)) {
        if (!gitCmd.pull()) {
            return -4;
        }
    } else {
        if (internal::customerRepoExists()) {
            if (!gitCmd.checkout()) {
                return -2;
            }
            if (!gitCmd.pull()) {
                return -4;
            }
            QString const result = gitCmd.commandResult().trimmed();
            if (result.contains("Already", Qt::CaseInsensitive)
             && result.contains("up", Qt::CaseInsensitive)
             && result.contains("to", Qt::CaseInsensitive)
             && result.contains("date", Qt::CaseInsensitive)) {
                qCritical() << internal::GIT_CUSTOMER_REPO_NO_UPDATE_NECESSARY;
                return internal::GIT_NOT_NECESSARY_CODE;
            } else
            if (result.contains(QRegularExpression("[Uu]pdating\\s+[a-z0-9]{6,}\\.\\.[a-z0-9]{6,}"))) {
                // Updating 49a97f5..13a0321
                qCritical() << internal::GIT_CUSTOMER_REPO_UPDATED;
                return internal::GIT_UPDATED_CODE;
            }
        } else {
            if (!gitCmd.clone()) {
                return -3;
            }
        }
    }

    //int const machineNr = read1stLineOfFile("/mnt/system_data/machine_nr");
    //int const customerNr = read1stLineOfFile("/mnt/system_data/cust_nr");
    //int const zoneNr = read1stLineOfFile("/mnt/system_data/zone_nr");

    return 0;
}