// SPDX-FileCopyrightText: 2022 Plata Hill <plata.hill@kdemail.net>
// SPDX-License-Identifier: LGPL-2.1-or-later

#pragma once

#include "fetcherimpl.h"
#include "types.h"

#include <QObject>
#include <QQmlEngine>

#include <memory>

class QNetworkAccessManager;
class QNetworkReply;
class QNetworkRequest;
class QString;

class Fetcher : public QObject
{
    Q_OBJECT
    QML_ELEMENT
    QML_SINGLETON

    Q_PROPERTY(unsigned int favoritesPercentage READ favoritesPercentage NOTIFY favoritesPercentageChanged)

public:
    static Fetcher &instance()
    {
        static Fetcher _instance;
        QJSEngine::setObjectOwnership(&_instance, QJSEngine::ObjectOwnership::CppOwnership);
        return _instance;
    }

    static Fetcher *create(QQmlEngine *, QJSEngine *)
    {
        return &instance();
    }

    Q_INVOKABLE void fetchFavorites(bool force = false);
    Q_INVOKABLE void fetchGroups();
    Q_INVOKABLE void fetchGroup(const QString &url, const GroupId &groupId);
    Q_INVOKABLE void fetchProgramDescription(const ChannelId &channelId, const ProgramId &programId, const QString &url);
    Q_INVOKABLE QString image(const QString &url);
    void setImpl(std::unique_ptr<FetcherImpl> fetcherImpl);

private:
    Fetcher();

    unsigned int favoritesPercentage();
    void setFavoritesPercentage(unsigned int percentage);

    void removeImage(const QString &url);

    unsigned int m_favoritesPercentage;
    std::unique_ptr<FetcherImpl> m_fetcherImpl;

Q_SIGNALS:
    void favoritesPercentageChanged(unsigned int percentage);

    void startedFetchingGroup(const GroupId &id);
    void groupUpdated(const GroupId &id);

    void startedFetchingChannel(const ChannelId &id);
    void finishedFetchingChannel(const ChannelId &id);
    void channelUpdated(const ChannelId &id);

    void programDescriptionUpdated(const ProgramId &id, const QString &description);

    void errorFetchingGroup(const GroupId &id, const Error &error);
    void errorFetchingChannel(const ChannelId &id, const Error &error);

    void imageDownloadFinished(const QString &url);
    void errorDownloadingImage(const QString &url, const Error &error);
};
