#ifndef PATCHDOWNLOADER_H
#define PATCHDOWNLOADER_H

#include <QObject>
#include <QTimer>
#include <QDate>
#include <QDir>
#include <QSettings>
#include <QMap>
#include "models/downloader.h"

struct Patch {
    QUrl url;
    QString md5_hash;
    QString datetime;
    QString name;
};

class PatchDownloader : public QObject
{
    Q_OBJECT
public:
    explicit PatchDownloader(QSettings* settings, QObject *parent = nullptr);
    ~PatchDownloader();
    void enableAutoUpdate();
    void disableAutoUpdate();
    void stopAllDownloads();
    void startAllDownloads();
    QString getPredictedDownloadSizeFormatted();
    QString getDatabasePathByPatchName(QString name);

public slots:
    void checkForUpdates();

private slots:
    void onDownloaderCompleted(Downloader* downloader_ptr);
    void onDownloaderProgressChanged(Downloader* downloader_ptr);

signals:
    void checkForUpdatesStarted();
    void checkForUpdatesFinished();
    void getPatchListError();
    void removeFileError(QString filename);
    void downloadNewFilesError();

    void downloadCompleted();
    void downloadStarted();
    void progressChanged(quint64 bytesDownloaded, quint64 bytesTotal,
                         QString download_speed_formatted,
                         QString elapsed_time_formatted);

    void patchDateChanged(QString patch_name, QDate patch_date);

private:
    int versionFromPatchFilename(QString filename);
    bool updatePatchList();
    bool removeOldPatchesFromDirecrory();
    bool addMissingPatchesToDownloadList();

private:

    QSettings* app_settings;
    quint8 active_downloads_number = 0;

    const QDir patch_download_dir;
    const QStringList all_patch_names = {"sound", "text", "image", "loadscreen", "texture", "font", "video"};

    QTimer update_check_timer;

    QMap<QString, Downloader*> downloads_list;
    QMap<QString, Patch> patch_data;
};

#endif // PATCHDOWNLOADER_H
