#ifndef INCLUDEILEDOWNLOADER_H
#define INCLUDEILEDOWNLOADER_H

#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QFile>
#include <QTime>
#include <QByteArray>

class Downloader : public QObject
{
    Q_OBJECT

public:
    explicit Downloader(QObject *parent = 0);
private:
    Q_DISABLE_COPY(Downloader)

public:
    virtual ~Downloader();

    QUrl getUrl();
    void setUrl(const QUrl& _url);
    void waitForDownloaded();

    bool isStarted();
    double getPercent();
    quint64 getBytesTotal();
    quint64 getBytesDownloaded();
    quint64 getElapsedTime();
    quint64 getSpeed();
    static QString getSizeFormatted(quint64 bytes);
    static QString getSpeedFormatted(quint64 speed_bytes_per_sec);
    static QString getElapsedTimeFormatted(quint64 elapsed_time_secs);

signals:
    void downloadFinished(Downloader* this_downloader_ptr);
    void progressChanged(Downloader* this_downloader_ptr);

public slots:
    void start();
    void updateDownloadSpeedLimit(int bytes_per_sec);
    void stop();

private slots:
    void onDownloadProgressChanged(qint64 bytesReceived, qint64 bytesTotal);
    void onDownloadFinished(QNetworkReply* pReply);
    void onReadyRead();

public:
    QFile* targetFile {nullptr};
    QByteArray* targetBytearray {nullptr};

private:
    QTime downloadTime;
    quint64 download_speed; // bytes per second

    quint64 bytes_total;
    quint64 bytes_downloaded;

    quint64 bytesReceivedBeforeSecond; // Нужны для подсчёта текущей скорости скачивания, а не
    quint64 timeElapsedBeforeSecond;   // средней за всё время.

    bool busy;
    QUrl url;
    QNetworkReply* m_CurrentReply {nullptr};
    QNetworkAccessManager m_WebCtrl;

    unsigned download_speed_limit {0};
};

#endif // INCLUDEILEDOWNLOADER_H
