#ifndef DATAMANAGER_H
#define DATAMANAGER_H

#include <QObject>
#include <QHash>
#include <QQueue>
#include <QVariant>
#include <QPointer>
#include <QTimer>
#include <QDateTime>
#include <QMutexLocker>
#include <QReadWriteLock>

class HttpRequestManager;
class DataManager : public QObject
{
    Q_OBJECT
    Q_DISABLE_COPY(DataManager) //禁止拷贝，等价于：DataManager(const DataManager&) = delete; DataManager& operator=(const DataManager&) = delete;

public:
    struct CacheEntry
    {
        QVariant data;
        QDateTime timestamp;
        int accessCount = 0;
        bool isUpdating = false;
        //QSet<QObject*> pendingRequests;
    };

    static DataManager* instance();

    void registerDataSource(const QString& dataKey, std::function<QVariant()> fetcher);
    void registerHttpDataSource(const QString& dataKey, const QUrl& url, const QByteArray& method = "GET",
                                const QByteArray& body = QByteArray(), const QMap<QByteArray, QByteArray>& headers = {});
    QVariant getCacheData(const QString& dataKey);
    bool hasData(const QString& dataKey);
    void requestData(const QString& dataKey, QObject* requester);
    void setCacheTimeout(int seconds);
    HttpRequestManager* httpManager();

signals:
    void dataUpdated(const QString& dataKey, const QVariant& data,  const QDateTime& timestamp);
    void cacheInvalidated(const QString& dataKey);

public slots:
    void invalidateCache(const QString& dataKey = QString());
    void processRequestQueue();

    void handleHttpDataReceived(const QString& dataKey, const QVariant& data);
    void handleHttpRequsetFailed(const QString& dataKey, const QVariant& data);

private:
    struct RequestInfo
    {
        QString dataKey;
        //QObject* requester;
        QPointer<QObject> requester;
    };

    explicit DataManager();
    ~DataManager();

    void triggerDataUpdate(const QString& dataKey);

    QHash<QString, CacheEntry> m_cache;
    QHash<QString, std::function<QVariant()>> m_dataSources;
    QSet<QString> m_pendingUpdates;
    QQueue<RequestInfo> m_requestQueue;
    QTimer m_requestTimer;
    QReadWriteLock m_cacheLock;
    QMutex m_requestMutex;
    HttpRequestManager* m_httpManager;
    int m_cacheTimeout = 300; //默认5分钟
    int m_minRefreshInterval = 100; //最小刷新间隔(ms)
};

#endif
