#include "mainwindow.h"
#include "skin.h"

#include <QApplication>
#include <QFile>
#include <QTextCodec>
#include <QLockFile>
#include <QtGlobal>
#include <QtGlobal>
#include <QMessageBox>
#include <QThread>
#include <QtConcurrent/QtConcurrentRun>
#include <QDir>
#include <QString>
#include <QDate>
#include <QtMessageHandler>

#include <stdio.h>
#include <stdlib.h>

void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QByteArray localMsg = msg.toUtf8();
    const char * format = "[" + QDate::currentDate().toString(Qt::ISODate).toUtf8() + " " + QTime::currentTime().toString(Qt::ISODate).toUtf8() + "]";
    switch (type) {
    case QtDebugMsg:
        fprintf(stderr, "%s    DEB: %s\n", format, localMsg.constData());
        break;
    case QtInfoMsg:
        fprintf(stderr, "%s    INF: %s\n", format, localMsg.constData());
        break;
    case QtWarningMsg:
        fprintf(stderr, "%s    WAR: %s\n", format, localMsg.constData());
        break;
    case QtCriticalMsg:
        fprintf(stderr, "%s    CRT: %s\n", format, localMsg.constData());
        break;
    case QtFatalMsg:
        fprintf(stderr, "%s    FAT: %s\n", format, localMsg.constData());
        abort();
    }
}

int main(int argc, char *argv[]){
    //if (argc <= 1 || (argc > 1 && std::string(argv[1]) != std::string("-S") && std::string(argv[1]) != "-prelaunched"))
    //    return 0;

    freopen("log.txt", "w", stdout);
    freopen("log.txt", "a", stderr);

    // if it's later than 25.02.2018 - return. That's for temporary version
    //long long cur_time = time(0);
    //if (cur_time >= 1520629200)
    //    return 0;

    setbuf(stdout, NULL);
    setbuf(stderr, NULL);
    setvbuf (stdout, NULL, _IONBF, BUFSIZ);
    setvbuf (stderr, NULL, _IONBF, BUFSIZ);/**/
    qInstallMessageHandler(myMessageOutput);// вывод логов в файл

    QApplication a(argc, argv);

    QLockFile lockFile(QDir::temp().absoluteFilePath("rulotro.lock"));
    if(!lockFile.tryLock(100)){
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setText("Приложение уже запущено.\nРазрешено запускать только один экземпляр приложения.");
        msgBox.exec();
        return 1;
    }

    MainWindow::getInstance()->show();

    QFile styleF;
    QString skin = Skin::getInstance()->getSkinName();
    styleF.setFileName(QApplication::applicationDirPath() + "styles/" + skin + "/style.css");
    styleF.open(QFile::ReadOnly);
    QString qssStr = styleF.readAll();

    qApp->setStyleSheet(qssStr);

    MainWindow::getInstance()->show();

    auto result = a.exec();
    lockFile.unlock();
    return result;
}

