/*
    Copyright (c) 2006 - 2007 Volker Krause <vkrause@kde.org>

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

    This library is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "collection.h"
#include "collection_p.h"
#include "entity_p.h"

#include "attributefactory.h"
#include "cachepolicy.h"
#include "collectionrightsattribute_p.h"
#include "collectionstatistics.h"
#include "entitydisplayattribute.h"

#include <QtCore/QDebug>
#include <QtCore/QHash>
#include <QtCore/QString>
#include <QtCore/QStringList>

#include <QUrl>
#include <QUrlQuery>

using namespace Akonadi;

uint Akonadi::qHash(const Akonadi::Collection &collection)
{
    return ::qHash(collection.id());
}

/**
 * Helper method for assignment operator and copy constructor.
 */
static void assignCollectionPrivate(QSharedDataPointer<CollectionPrivate> &one,
                                    const QSharedDataPointer<CollectionPrivate> &other)
{
    // We can't simply do one = other here, we have to use a temp.
    // Otherwise ProtocolHelperTest::testParentCollectionAfterCollectionParsing()
    // will break.
    //
    // The reason are assignments like
    //   col = col.parentCollection()
    //
    // Here, parentCollection() actually returns a reference to a pointer owned
    // by col. So when col (or rather, it's private class) is deleted, the pointer
    // to the parent collection and therefore the reference becomes invalid.
    //
    // With a single-line assignment here, the parent collection would be deleted
    // before it is assigned, and therefore the resulting object would point to
    // uninitalized memory.
    QSharedDataPointer<CollectionPrivate> temp = other;
    one = temp;
}

class CollectionRoot : public Collection
{
public:
    CollectionRoot()
        : Collection(0)
    {
        setContentMimeTypes({ Collection::mimeType() });

        // The root collection is read-only for the users
        setRights(Collection::ReadOnly);
    }
};

Q_GLOBAL_STATIC(CollectionRoot, s_root)

Collection::Collection()
    : d_ptr(new CollectionPrivate)
{
    static int lastId = -1;
    d_ptr->mId = lastId--;
}

Collection::Collection(Id id)
    : d_ptr(new CollectionPrivate(id))
{
}

Collection::Collection(const Collection &other)
{
    assignCollectionPrivate(d_ptr, other.d_ptr);
}

Collection::~Collection()
{
}

void Collection::setId(Collection::Id identifier)
{
    d_ptr->mId = identifier;
}

Collection::Id Collection::id() const
{
    return d_func()->mId;
}

void Collection::setRemoteId(const QString &id)
{
    d_ptr->mRemoteId = id;
}

QString Collection::remoteId() const
{
    return d_ptr->mRemoteId;
}

void Collection::setRemoteRevision(const QString &revision)
{
    d_ptr->mRemoteRevision = revision;
}

QString Collection::remoteRevision() const
{
    return d_ptr->mRemoteRevision;
}

bool Collection::isValid() const
{
    return (d_ptr->mId >= 0);
}

bool Collection::operator==(const Collection &other) const
{
    // Invalid collections are the same, no matter what their internal ID is
    return (!isValid() && !other.isValid()) || (d_ptr->mId == other.d_ptr->mId);
}

bool Akonadi::Collection::operator!=(const Collection &other) const
{
    return (isValid() || other.isValid()) && (d_ptr->mId != other.d_ptr->mId);
}

Collection &Collection ::operator=(const Collection &other)
{
    if (this != &other) {
        assignCollectionPrivate(d_ptr, other.d_ptr);
    }

    return *this;
}

bool Akonadi::Collection::operator<(const Collection &other) const
{
    return d_ptr->mId < other.d_ptr->mId;
}

void Collection::addAttribute(Attribute *attr)
{
    Q_ASSERT(attr);
    Attribute *existing = d_ptr->mAttributes.value(attr->type());
    if (existing) {
        if (attr == existing) {
            return;
        }
        d_ptr->mAttributes.remove(attr->type());
        delete existing;
    }
    d_ptr->mAttributes.insert(attr->type(), attr);
    d_ptr->mDeletedAttributes.remove(attr->type());
}

void Collection::removeAttribute(const QByteArray &type)
{
    d_ptr->mDeletedAttributes.insert(type);
    delete d_ptr->mAttributes.take(type);
}

bool Collection::hasAttribute(const QByteArray &type) const
{
    return d_ptr->mAttributes.contains(type);
}

Attribute::List Collection::attributes() const
{
    return d_ptr->mAttributes.values();
}

void Akonadi::Collection::clearAttributes()
{
    Q_FOREACH (Attribute *attr, d_ptr->mAttributes) {
        d_ptr->mDeletedAttributes.insert(attr->type());
        delete attr;
    }
    d_ptr->mAttributes.clear();
}

Attribute *Collection::attribute(const QByteArray &type) const
{
    return d_ptr->mAttributes.value(type);
}

Collection &Collection::parentCollection()
{
    if (!d_ptr->mParent) {
        d_ptr->mParent = new Collection();
    }
    return *(d_ptr->mParent);
}

Collection Collection::parentCollection() const
{
    if (!d_ptr->mParent) {
        return *(s_defaultParentCollection);
    } else {
        return *(d_ptr->mParent);
    }
}

void Collection::setParentCollection(const Collection &parent)
{
    delete d_ptr->mParent;
    d_ptr->mParent = new Collection(parent);
}

QString Collection::name() const
{
    return d_func()->name;
}

QString Collection::displayName() const
{
    const EntityDisplayAttribute *const attr = attribute<EntityDisplayAttribute>();
    const QString displayName = attr ? attr->displayName() : QString();
    return !displayName.isEmpty() ? displayName : d_func()->name;
}

void Collection::setName(const QString &name)
{
    Q_D(Collection);
    d->name = name;
}

Collection::Rights Collection::rights() const
{
    CollectionRightsAttribute *attr = attribute<CollectionRightsAttribute>();
    if (attr) {
        return attr->rights();
    } else {
        return AllRights;
    }
}

void Collection::setRights(Rights rights)
{
    CollectionRightsAttribute *attr = attribute<CollectionRightsAttribute>(AddIfMissing);
    attr->setRights(rights);
}

QStringList Collection::contentMimeTypes() const
{
    return d_func()->contentTypes;
}

void Collection::setContentMimeTypes(const QStringList &types)
{
    Q_D(Collection);
    if (d->contentTypes != types) {
        d->contentTypes = types;
        d->contentTypesChanged = true;
    }
}

QUrl Collection::url(UrlType type) const
{
    QUrlQuery query;
    query.addQueryItem(QStringLiteral("collection"), QString::number(id()));
    if (type == UrlWithName) {
        query.addQueryItem(QStringLiteral("name"), name());
    }

    QUrl url;
    url.setScheme(QStringLiteral("akonadi"));
    url.setQuery(query);
    return url;
}

Collection Collection::fromUrl(const QUrl &url)
{
    if (url.scheme() != QLatin1String("akonadi")) {
        return Collection();
    }

    const QString colStr = QUrlQuery(url).queryItemValue(QStringLiteral("collection"));
    bool ok = false;
    Collection::Id colId = colStr.toLongLong(&ok);
    if (!ok) {
        return Collection();
    }

    if (colId == 0) {
        return Collection::root();
    }

    return Collection(colId);
}

Collection Collection::root()
{
    return *s_root;
}

QString Collection::mimeType()
{
    return QStringLiteral("inode/directory");
}

QString Akonadi::Collection::virtualMimeType()
{
    return QStringLiteral("application/x-vnd.akonadi.collection.virtual");
}

QString Collection::resource() const
{
    return d_func()->resource;
}

void Collection::setResource(const QString &resource)
{
    Q_D(Collection);
    d->resource = resource;
}

QDebug operator <<(QDebug d, const Akonadi::Collection &collection)
{
    return d << "Collection ID:" << collection.id()
           << "   remote ID:" << collection.remoteId() << endl
           << "   name:" << collection.name() << endl
           << "   url:" << collection.url() << endl
           << "   parent:" << collection.parentCollection().id() << collection.parentCollection().remoteId() << endl
           << "   resource:" << collection.resource() << endl
           << "   rights:" << collection.rights() << endl
           << "   contents mime type:" << collection.contentMimeTypes() << endl
           << "   isVirtual:" << collection.isVirtual() << endl
           << "   " << collection.cachePolicy() << endl
           << "   " << collection.statistics();
}

CollectionStatistics Collection::statistics() const
{
    return d_func()->statistics;
}

void Collection::setStatistics(const CollectionStatistics &statistics)
{
    Q_D(Collection);
    d->statistics = statistics;
}

CachePolicy Collection::cachePolicy() const
{
    return d_func()->cachePolicy;
}

void Collection::setCachePolicy(const CachePolicy &cachePolicy)
{
    Q_D(Collection);
    d->cachePolicy = cachePolicy;
    d->cachePolicyChanged = true;
}

bool Collection::isVirtual() const
{
    return d_func()->isVirtual;
}

void Akonadi::Collection::setVirtual(bool isVirtual)
{
    Q_D(Collection);

    d->isVirtual = isVirtual;
}

void Collection::setEnabled(bool enabled)
{
    Q_D(Collection);

    d->enabledChanged = true;
    d->enabled = enabled;
}

bool Collection::enabled() const
{
    Q_D(const Collection);

    return d->enabled;
}

void Collection::setLocalListPreference(Collection::ListPurpose purpose, Collection::ListPreference preference)
{
    Q_D(Collection);

    switch (purpose) {
    case ListDisplay:
        d->displayPreference = preference;
        break;
    case ListSync:
        d->syncPreference = preference;
        break;
    case ListIndex:
        d->indexPreference = preference;
        break;
    }
    d->listPreferenceChanged = true;
}

Collection::ListPreference Collection::localListPreference(Collection::ListPurpose purpose) const
{
    Q_D(const Collection);

    switch (purpose) {
    case ListDisplay:
        return d->displayPreference;
    case ListSync:
        return d->syncPreference;
    case ListIndex:
        return d->indexPreference;
    }
    return ListDefault;
}

bool Collection::shouldList(Collection::ListPurpose purpose) const
{
    if (localListPreference(purpose) == ListDefault) {
        return enabled() || referenced();
    }
    return (localListPreference(purpose) == ListEnabled);
}

void Collection::setShouldList(ListPurpose purpose, bool list)
{
    if (localListPreference(purpose) == ListDefault) {
        setEnabled(list);
    } else {
        setLocalListPreference(purpose, list ? ListEnabled : ListDisabled);
    }
}

void Collection::setReferenced(bool referenced)
{
    Q_D(Collection);

    d->referencedChanged = true;
    d->referenced = referenced;
}

bool Collection::referenced() const
{
    Q_D(const Collection);

    return d->referenced;
}

void Collection::setKeepLocalChanges(const QSet<QByteArray> &parts)
{
    Q_D(Collection);

    d->keepLocalChanges = parts;
}

QSet<QByteArray> Collection::keepLocalChanges() const
{
    Q_D(const Collection);

    return d->keepLocalChanges;
}

AKONADI_DEFINE_PRIVATE(Akonadi::Collection)
