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

#include <QFileInfo>
#include <QApplication>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QString>
#include <QStringList>
#include <QTimer>
#include <stdio.h>

DownloadManager::DownloadManager(QObject *parent)
    : QObject(parent), downloadedCount(0), totalCount(0)
{
}

void DownloadManager::append(const QStringList &urlList){
    foreach (QString url, urlList)
        append(QUrl::fromEncoded(url.toLocal8Bit()));

    if (downloadQueue.isEmpty())
        QTimer::singleShot(0, this, SIGNAL(finished()));
}

void DownloadManager::append(const QUrl &url){
    qDebug("%s:%i: %s%s", __FILE__, __LINE__, "Добавлен: ", url.fileName().toLocal8Bit().data());
    if (downloadQueue.isEmpty())
        QTimer::singleShot(0, this, SLOT(startNextDownload()));

    downloadQueue.enqueue(url);
    ++totalCount;
    qDebug("%s:%i: %s%i", __FILE__, __LINE__, "Загрузок в списке: ", totalCount);
}

void DownloadManager::startNextDownload()
{
    App *app = &App::getInstance();

    if (downloadQueue.isEmpty()) {
        app->helper->setState("free");// говорим что приложение освободилось
        qDebug("%s:%i: %s%d/%d", __FILE__, __LINE__, "Загрузка завершена. Загружено файлов: ", downloadedCount, totalCount);
        emit finished();
        return;
    }

    QUrl url = downloadQueue.dequeue();
    QString filename = QFileInfo(url.path()).fileName();
    output.setFileName(QApplication::applicationDirPath() + "/data/" + filename);
    qDebug("%s:%i: %s%s", __FILE__, __LINE__, "Начата загрузка файла: ", filename.toLocal8Bit().data());
    // Проверяем целостность файла и игнорируем в случае если он цел
    QString hash = FileSystem::fileHash(QApplication::applicationDirPath() + "/data/" + filename, QCryptographicHash::Md5);
    QStringList pname = output.fileName().split("/");
    QStringList ptype = pname.last().split("_");
    qDebug() << ptype.first();
    QString keyname = ptype.first();
    if(keyname == "loadscreens") keyname = "screens";
    if(hash == app->config->getValue("Hashes", ptype.first()) && app->config->getValue("Editor", keyname) == "true"){
        qDebug("%s:%i: %s%s", __FILE__, __LINE__, "Проверка хэша успешно завершена: ", filename.toLocal8Bit().data());
        startNextDownload();
        return;
    }

    qDebug("%s:%i: %s%s", __FILE__, __LINE__, "Хэш файла не совпал: ", filename.toLocal8Bit().data());
    QStringList parsename = filename.split("_");
    QString name = parsename[0] + "Status";
    download_name = parsename[0];
    app->writtenLabel = app->window->ui->mainbox->findChild<QLabel *>(name);

    if (!output.open(QIODevice::WriteOnly)) {
        qCritical("%s:%i: %s%s", __FILE__, __LINE__, "Произошла остановка скачивания ", filename.toLocal8Bit().data());
        /*fprintf(stderr, "Problem opening save file '%s' for download '%s': %s\n",
                qPrintable(filename), url.toEncoded().constData(),
                qPrintable(output.errorString()));*/
        if(app->writtenLabel != nullptr) app->writtenLabel->setText("Не удалась");
        startNextDownload();
        return;
    }

    qInfo("%s:%i: %s%s", __FILE__, __LINE__, "Начинаем скачивание ", url.fileName().toLocal8Bit().data());

    app->helper->setState("busy");// говорим что приложение занято

    QNetworkRequest request(url);
    currentDownload = manager.get(request);
    connect(this, SIGNAL(cancelDownload()), currentDownload, SLOT(abort()));
    connect(currentDownload, SIGNAL(downloadProgress(qint64,qint64)),
            SLOT(downloadProgress(qint64,qint64)));
    connect(currentDownload, SIGNAL(finished()),
            SLOT(downloadFinished()));
    connect(currentDownload, SIGNAL(readyRead()),
            SLOT(downloadReadyRead()));

    // prepare the output

    downloadTime.start();
}

void DownloadManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
    double speed = bytesReceived * 1000.0 / downloadTime.elapsed();
    double percent =  double(std::ceil(((double)bytesReceived/ bytesTotal) * 100 * 10)) / 10.0;
    QString unit;
    if (speed < 1024) {
        unit = "bytes/sec";
    } else if (speed < 1024*1024) {
        speed /= 1024;
        unit = "kB/s";
    } else {
        speed /= 1024*1024;
        unit = "MB/s";
    }
    QString speedtext = QString::fromLatin1("%1 %2").arg(speed, 3, 'f', 1).arg(unit);
    QString percenttext = QString::fromLatin1("%1").arg(percent, 3);

    App *app = &App::getInstance();
    if(app->writtenLabel != nullptr) app->writtenLabel->setText("Загрузка ... <br/>" + percenttext+ "% (" + speedtext + ")");
}

void DownloadManager::downloadFinished()
{
    output.close();
    App *app = &App::getInstance();
    app->helper->setState("free");// говорим что приложение освободилось

    if (currentDownload->error()) {
         qWarning("%s:%i: %s%s", __FILE__, __LINE__, "Загрузка не удалась: ", currentDownload->errorString().toLocal8Bit().data());
        //fprintf(stderr, "Failed: %s\n", qPrintable(currentDownload->errorString()));
        if(app->writtenLabel != nullptr) app->writtenLabel->setText("Не удалась.");
    } else {       
        if(app->writtenLabel != nullptr) app->writtenLabel->setText("Готово");
        qInfo("%s:%i: %s", __FILE__, __LINE__, "Все загрузки завершены. Загрузчик завершил свою работу.");
        ++downloadedCount;
        app->network->getPaths();

    }

    currentDownload->deleteLater();
    startNextDownload();
}

void DownloadManager::downloadReadyRead(){
    output.write(currentDownload->readAll());
}

void DownloadManager::abortDownload(QString name){
    App *app = &App::getInstance();
    if(download_name == name){
       if(app->state != "free" &&  currentDownload != NULL && currentDownload->isOpen()) {
            qDebug() << "Прерываем закачку " + download_name;
            qInfo("%s:%i: %s%s", __FILE__, __LINE__, "Пользователь прервал закачку файла ", download_name.toLocal8Bit().data());
            if(app->writtenLabel != nullptr) app->writtenLabel->setText("Не выбран");
            currentDownload->abort();

       }
    }
}
