#include "app.h"
#include "filesystem.h"

#include <QApplication>
#include <QFile>
#include <QTextCodec>
#include <QLockFile>
#include <QtGlobal>
#include <QDebug>
#include <QScreen>
#include <stdio.h>
#include <stdlib.h>

#include <QThread>
#include <QtConcurrent/QtConcurrentRun>

void myMessageOutput(QtMsgType type, const QMessageLogContext &, 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]) != "-prelaunched")) {
        QApplication a(argc, argv);
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setText("Запуск Наследия невозможен без лаунчера. Используйте лаунчер Наследия для запуска приложения!");
        msgBox.exec();
        a.exit(0);
        return 0;
    }

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

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

    float scale_factor = 1;

    if (!FileSystem::fileExists("dpi.stml")) {
        QApplication a(argc, argv);
        std::vector<float> dpi_scales = {1, 1.5, 2, 2.5};

        float current_dpi = ((QGuiApplication*)QCoreApplication::instance())->primaryScreen()->physicalDotsPerInch() / 96.0;

        qDebug() << "No value. Detected " << current_dpi;

        float best_scale = 1;
        for (float scale : dpi_scales) {
            qDebug() << "Looking at " << scale << " Current diff = " << std::abs(current_dpi - scale) << ", best diff = " << std::abs(current_dpi - best_scale);
            if (std::abs(current_dpi - scale) < std::abs(current_dpi - best_scale))
                best_scale = scale;
        }

        qDebug() << "Using dpi scale factor " << best_scale;

        QFile file("dpi.stml");
        file.open(QIODevice::WriteOnly);
        QTextStream writeStream(&file);
        writeStream << best_scale;
        file.close();

        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Information);
        msgBox.setText("Первоначальная настройка завершена. Пожалуйста, перезапустите приложение");
        msgBox.exec();
        a.exit(0);
        return 0;
    } else {
        QFile file("dpi.stml");
        file.open(QIODevice::ReadOnly);
        QString dpi = file.readLine();
        scale_factor = dpi.toDouble();
        qDebug() << dpi;
        qputenv("QT_SCALE_FACTOR", dpi.toLatin1());
    }

    QApplication a(argc, argv);

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

    MainWindow w(scale_factor);

    auto result = a.exec();

    lockFile.unlock();
    return result;
}

