#include "launcher.h"
#include "ui_launcher.h"

GIFAnimationDemoWidget::GIFAnimationDemoWidget( QWidget* parent ) :
    QWidget( parent, Qt::Window | Qt::FramelessWindowHint  ), ui( new Ui::GIFAnimationDemoWidget ) {

    ui->setupUi(this);
    setWindowTitle("ВКО: Наследие - система обновлений");
    ui->lbHint->setText("Получение списка файлов...");
    movie = new QMovie(":/second.gif");
    ui->lbMovie->setMovie(movie);
    movie->setScaledSize(QSize(ui->lbMovie->width(), ui->lbMovie->height()));
    movie->start();

    QString response = getFilelist("http://translate.lotros.ru/upload/launcher/filelist.txt");

    QFuture<void> future = QtConcurrent::run([=]() {
        start(response);
    });
}

GIFAnimationDemoWidget::~GIFAnimationDemoWidget() {
    delete ui;
}

void GIFAnimationDemoWidget::start(QString filelist) {
    ui->lbHint->setText("Проверка и скачивание файлов...");

    QStringList templist = filelist.split("\r\n");

    foreach(const QString &str, templist){
        QString path = str;
        QStringList list = path.replace("release/", "").split("|");

        path = list[0];
        if (path.size() == 0)
            continue;

        qDebug() << path;

        if (fileExists(path)) {
            QString hash = fileHash(list[0], QCryptographicHash::Md5); // Hashes match - file is ok. Passing it;
            qDebug() << path << " " << hash << " " << list[1];
            if (hash == list[1])
                continue;
        }

        QFileInfo fileInfo(path);
        QString folder = fileInfo.dir().path();
        if (folder == ".") folder = "";
        makeFolder(folder);
        ui->lbHint->setText("Загрузка " + path);
        downloadFile ("http://translate.lotros.ru/upload/launcher/release/" + path, QApplication::applicationDirPath() + "/" + folder);
    }

    ui->lbHint->setText("Подготовка к запуску ...");
    QProcess process;
    process.startDetached("Legacy.exe -prelaunched");
    process.waitForFinished(-1);
    exit(0);
}

QString GIFAnimationDemoWidget::fileHash(const QString &fileName, QCryptographicHash::Algorithm hashAlgorithm) {
    QFile file(fileName);
    if (file.open(QIODevice::ReadOnly)) {
        QByteArray fileData = file.readAll();
        QByteArray hashData = QCryptographicHash::hash(fileData, hashAlgorithm);
        return hashData.toHex();
    }
    return QByteArray();
}

bool GIFAnimationDemoWidget::fileExists(QString path) {
    QFileInfo check_file(path);
    return check_file.exists() && check_file.isFile();
}

void GIFAnimationDemoWidget::makeFolder(QString path) {
    QString folder = QApplication::applicationDirPath();
    QStringList p = path.split("/");

    foreach(const QString &str, p){
        folder = folder + "/" + str;
        if (!(QDir(folder).exists() == true) ){
            QDir().mkdir(folder);
            qDebug() << "Создана папка " + folder;
        }
    }
}

void GIFAnimationDemoWidget::startNewAnimation() {
    delete movie;
    movie = new QMovie(":/second.gif");
    ui->lbMovie->setMovie(movie);
    movie->setScaledSize(QSize(ui->lbMovie->width(), ui->lbMovie->height()));
    movie->start();
}

QString GIFAnimationDemoWidget::getFilelist(const QString &url) {
    QNetworkAccessManager manager;
    QNetworkReply* reply = manager.get(QNetworkRequest(url));
    QEventLoop loop;
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();
    QString content;
    if (reply->error() != QNetworkReply::NoError){
        content = "error";
        // пишем в лог
        qDebug() << reply->errorString();
    }
    reply->deleteLater();
    content = reply->readAll();
    return content;
}



void GIFAnimationDemoWidget::downloadFile(const QString &url, const QString &aPathInClient) {
    QNetworkAccessManager m_NetworkMngr;
    QNetworkReply *reply= m_NetworkMngr.get(QNetworkRequest(url));
    QEventLoop loop;
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();
    QUrl aUrl(url);
    QFileInfo fileInfo=aUrl.path();
    QFile file(aPathInClient+ "/" + fileInfo.fileName());
    file.remove();
    file.open(QIODevice::WriteOnly);
    file.write(reply->readAll());
}
