// Copyright (C) 2026 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Qt-Security score:significant reason:default


#ifndef QCONTACTMEMORYBACKEND_P_H
#define QCONTACTMEMORYBACKEND_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include <QtContacts/qcontact.h>
#include <QtContacts/qcontactmanager.h>
#include <QtContacts/qcontactmanagerengine.h>
#include <QtContacts/qcontactchangeset.h>
#include <QtContacts/qcontactmanagerenginefactory.h>

QT_BEGIN_NAMESPACE_CONTACTS

class QContactMemoryEngine;

class QContactMemoryEngineFactory : public QContactManagerEngineFactory
{
    Q_OBJECT
    Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QContactManagerEngineFactoryInterface" FILE "memory.json")
public:
    QContactManagerEngine* engine(const QMap<QString, QString> &parameters, QContactManager::Error*) override;
    QString managerName() const override;
};

class QContactMemoryEnginePrivate : public QSharedData
{
public:
    QContactMemoryEnginePrivate()
        : QSharedData()
        , m_refCount(QAtomicInt(1))
        , m_selfContactId()
        , m_nextContactId(1)
        , m_anonymous(false)
    {
    }

    QContactMemoryEnginePrivate(const QContactMemoryEnginePrivate &other)
        : QSharedData(other),
        m_refCount(QAtomicInt(1)),
        m_selfContactId(other.m_selfContactId),
        m_nextContactId(other.m_nextContactId),
        m_anonymous(other.m_anonymous)
    {
    }

    ~QContactMemoryEnginePrivate()
    {
    }

    static QContactMemoryEnginePrivate *data(QContactMemoryEngine *engine);

    QAtomicInt m_refCount;
    QString m_id;                                  // the id parameter value

    QContactId m_selfContactId;               // the "MyCard" contact id
    QList<QContact> m_contacts;               // list of contacts
    QMultiHash<QContactCollectionId, QContactId> m_contactsInCollections;   // hash of contacts for each collection
    QHash<QContactCollectionId, QContactCollection> m_idToCollectionHash; // hash of id to the collection identified by that id
    QList<QContactId> m_contactIds;           // list of contact Id's
    QList<QContactRelationship> m_relationships;   // list of contact relationships
    QMap<QContactId, QList<QContactRelationship> > m_orderedRelationships; // map of ordered lists of contact relationships
    QList<QString> m_definitionIds;                // list of definition types (id's)
    quint32 m_nextContactId;
    bool m_anonymous;                              // Is this backend ever shared?
    QString m_managerUri;                        // for faster lookup.


    void emitSharedSignals(QContactChangeSet *cs)
    {
        for (QContactManagerEngine *engine : std::as_const(m_sharedEngines))
            cs->emitSignals(engine);
    }

    void emitSharedSignals(QContactCollectionChangeSet *cs)
    {
        for (QContactManagerEngine *engine : std::as_const(m_sharedEngines))
            cs->emitSignals(engine);
    }

    QList<QContactManagerEngine*> m_sharedEngines;   // The list of engines that share this data
};


class QContactMemoryEngine : public QContactManagerEngine
{
    Q_OBJECT

public:
    static QContactMemoryEngine *createMemoryEngine(const QMap<QString, QString> &parameters);

    ~QContactMemoryEngine();

    /* URI reporting */
    QString managerName() const override;
    QMap<QString, QString> managerParameters() const override;
    QMap<QString, QString> idInterpretationParameters() const override;

    /*! \reimp */
    int managerVersion() const override {return 1;}

    virtual QList<QContactId> contactIds(const QContactFilter &filter, const QList<QContactSortOrder> &sortOrders, QContactManager::Error *error) const override;
    virtual QList<QContact> contacts(const QContactFilter &filter, const QList<QContactSortOrder> &sortOrders, const QContactFetchHint &fetchHint, QContactManager::Error *error) const override;
    virtual QContact contact(const QContactId &contactId, const QContactFetchHint &fetchHint, QContactManager::Error *error) const override;

    virtual bool saveContacts(QList<QContact> *contacts, QMap<int, QContactManager::Error> *errorMap, QContactManager::Error *error) override;
    virtual bool removeContacts(const QList<QContactId> &contactIds, QMap<int, QContactManager::Error> *errorMap, QContactManager::Error *error) override;

    /* "Self" contact id (MyCard) */
    virtual bool setSelfContactId(const QContactId &contactId, QContactManager::Error *error) override;
    virtual QContactId selfContactId(QContactManager::Error *error) const override;

    /* Relationships between contacts */
    virtual QList<QContactRelationship> relationships(const QString &relationshipType, const QContactId &participantId, QContactRelationship::Role role, QContactManager::Error *error) const override;
    virtual bool saveRelationships(QList<QContactRelationship> *relationships, QMap<int, QContactManager::Error> *errorMap, QContactManager::Error *error) override;
    virtual bool removeRelationships(const QList<QContactRelationship> &relationships, QMap<int, QContactManager::Error> *errorMap, QContactManager::Error *error) override;

    // Keep the base-class single-item and partial-save overloads visible: this
    // engine declares same-named helpers taking a QContactChangeSet (below),
    // which would otherwise hide the QContactManagerEngine virtuals.
    using QContactManagerEngine::saveContact;
    using QContactManagerEngine::removeContact;
    using QContactManagerEngine::saveContacts;
    using QContactManagerEngine::saveRelationship;
    using QContactManagerEngine::removeRelationship;

    // collections
    QContactCollectionId defaultCollectionId() const override;
    QContactCollection collection(const QContactCollectionId &collectionId, QContactManager::Error *error) override;
    QList<QContactCollection> collections(QContactManager::Error* error) override;
    bool saveCollection(QContactCollection* collection, QContactManager::Error* error) override;
    bool removeCollection(const QContactCollectionId& collectionId, QContactManager::Error* error) override;

    /*! \reimp */
    virtual bool validateContact(const QContact &contact, QContactManager::Error *error) const override
    {
        return QContactManagerEngine::validateContact(contact, error);
    }

    /* Asynchronous Request Support */
    virtual void requestDestroyed(QContactAbstractRequest *req) override;
    virtual bool startRequest(QContactAbstractRequest *req) override;
    virtual bool cancelRequest(QContactAbstractRequest *req) override;
    virtual bool waitForRequestFinished(QContactAbstractRequest *req, int msecs) override;

    /* Capabilities reporting */
    virtual bool isRelationshipTypeSupported(const QString &relationshipType, QContactType::TypeValues contactType) const override;
    virtual bool isFilterSupported(const QContactFilter &filter) const override;
    virtual QList<QMetaType::Type> supportedDataTypes() const override;
    /*! \reimp */
    virtual QList<QContactType::TypeValues> supportedContactTypes() const override
    {
        return QContactManagerEngine::supportedContactTypes();
    }
    virtual QList<QContactDetail::DetailType> supportedContactDetailTypes() const override
    {
        return QContactManagerEngine::supportedContactDetailTypes();
    }


protected:
    QContactMemoryEngine(QContactMemoryEnginePrivate *data);

protected:
    /* Implement "signal coalescing" for batch functions via change set */
    virtual bool saveContact(QContact *theContact, QContactChangeSet &changeSet, QContactManager::Error *error);
    virtual bool removeContact(const QContactId &contactId, QContactChangeSet &changeSet, QContactManager::Error *error);
    virtual bool saveRelationship(QContactRelationship *relationship, QContactChangeSet &changeSet, QContactManager::Error *error);
    virtual bool removeRelationship(const QContactRelationship &relationship, QContactChangeSet &changeSet, QContactManager::Error *error);

private:
    /* For partial save */
    bool saveContacts(QList<QContact> *contacts, QMap<int, QContactManager::Error> *errorMap, QContactManager::Error *error, const QList<QContactDetail::DetailType> &mask);
    bool saveContact(QContact *theContact, QContactChangeSet &changeSet, QContactManager::Error *error, const QList<QContactDetail::DetailType> &mask);
    void partiallySyncDetails(QContact *to, const QContact &from, const QList<QContactDetail::DetailType> &mask);

    void performAsynchronousOperation(QContactAbstractRequest *request);

    QContactMemoryEnginePrivate *d;
    static QMap<QString, QContactMemoryEnginePrivate*> engineDatas;

    friend class QContactMemoryEnginePrivate;
};

QT_END_NAMESPACE_CONTACTS

#endif // QCONTACTMEMORYBACKEND_P_H
