// SPDX-FileCopyrightText: 2026 Marco Allegretti
// SPDX-License-Identifier: EUPL-1.2

#pragma once

#include <QAbstractListModel>
#include <QDateTime>
#include <QHash>
#include <QList>
#include <QObject>
#include <QString>

#include <QtQmlIntegration/qqmlintegration.h>

#include <memory>

class FolioDelegate;
class HomeScreen;

struct ApplicationUsageEntry {
    QString storageId;
    int launchCount = 0;
    QDateTime lastUsed;
};

class ApplicationUsageStore : public QObject
{
    Q_OBJECT

public:
    explicit ApplicationUsageStore(HomeScreen *parent = nullptr);

    QList<ApplicationUsageEntry> entries() const;
    void recordUsage(const QString &storageId);

Q_SIGNALS:
    void usageChanged();

private:
    void load();
    void save();

    HomeScreen *m_homeScreen{nullptr};
    QHash<QString, ApplicationUsageEntry> m_entries;
};

class ApplicationUsageModel : public QAbstractListModel
{
    Q_OBJECT
    QML_ELEMENT
    QML_UNCREATABLE("")

public:
    enum Mode {
        RecentUsage,
        MostUsed,
    };

    enum Roles {
        DelegateRole = Qt::UserRole + 1,
        LaunchCountRole,
        LastUsedRole,
    };

    ApplicationUsageModel(HomeScreen *homeScreen = nullptr, ApplicationUsageStore *store = nullptr, Mode mode = RecentUsage);

    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
    QHash<int, QByteArray> roleNames() const override;

public Q_SLOTS:
    void rebuild();

private:
    HomeScreen *m_homeScreen{nullptr};
    ApplicationUsageStore *m_store{nullptr};
    Mode m_mode{RecentUsage};
    QList<ApplicationUsageEntry> m_entries;
    QList<std::shared_ptr<FolioDelegate>> m_delegates;
};