#include "utils.h"
#include "message_handler.h"

#include <QFile>
#include <QTextStream>
#include <QDebug>

int Utils::read1stLineOfFile(QString fileName) {
    QFile f(fileName);
    if (f.exists()) {
        if (f.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QTextStream in(&f);
            in.setCodec("UTF-8");
            while(!in.atEnd()) {
                return in.readLine().toInt();
            }
        }
    }
    return -1;
}

QString Utils::zoneName(quint8 i) {
    static constexpr char const *zName[] = {
        "",
        "purple",
        "blue",
        "yellow",
        "green",
        "yellow (mars)",
        "green (mars)"
    };
    if (i < (sizeof(zName)/sizeof(char const *))) {
        return zName[i];
    }
    return "N/A";
}

void Utils::printCriticalErrorMsg(QString const &errorMsg) {
    qCritical() << QString(80, '!');
    qCritical() << errorMsg;
    qCritical() << QString(80, '!');
}

void Utils::printInfoMsg(QString const &infoMsg) {
    qCritical() << QString(80, '=');
    qCritical() << infoMsg;
    qCritical() << QString(80, '=');

}

void Utils::printLineEditInfo(QStringList const &lines) {
    if (getDebugLevel() == LOG_DEBUG) {
        for (int i=0; i<lines.size(); ++i) {
            qInfo() << lines.at(i);
        } qInfo() << ""; qInfo() << "";
    }
}

QString Utils::getTariffLoadTime(QString fileName) {
    QFileInfo fInfo(fileName);
    if (fInfo.exists()) {
        QDateTime lastModifiedTime = fInfo.lastModified();
        if (lastModifiedTime.isValid()) {
            return lastModifiedTime.toString(Qt::ISODateWithMs);
        } else {
            printCriticalErrorMsg(fileName + " HAS INVALID MODIFIED-TIME");
            QDateTime birthTime = fInfo.birthTime();
            if (birthTime.isValid()) {
                return birthTime.toString(Qt::ISODateWithMs);
            } else {
                printCriticalErrorMsg(fileName + " HAS INVALID BIRTH-TIME");
            }
        }
    } else {
        printCriticalErrorMsg(fileName + " DOES NOT EXIST");
    }
    return "N/A";
}

QString Utils::rstrip(QString const &str) {
    int n = str.size() - 1;
    for (; n >= 0; --n) {
        if (!str.at(n).isSpace()) {
            return str.left(n + 1);
        }
    }
    return "";
}
