/*
    This file is part of the KDE Baloo Project
    SPDX-FileCopyrightText: 2014-2015 Vishesh Handa <vhanda@kde.org>

    SPDX-License-Identifier: LGPL-2.1-or-later
*/

#include "taglistjob.h"
#include "global.h"
#include "database.h"
#include "transaction.h"

#include <QStringList>

using namespace Baloo;

class TagListJob::Private {
public:
    QStringList tags;
};

TagListJob::TagListJob(QObject* parent)
    : KJob(parent)
    , d(new Private)
{
}

TagListJob::~TagListJob()
{
    delete d;
}

void TagListJob::start()
{
    Database *db = globalDatabaseInstance();
    if (!db->open(Database::ReadOnlyDatabase)) {
        setError(UserDefinedError);
        setErrorText(QStringLiteral("Failed to open the database"));
        emitResult();
        return;
    }

    QVector<QByteArray> tagList;
    {
        Transaction tr(db, Transaction::ReadOnly);
        tagList = tr.fetchTermsStartingWith("TAG-");
    }
    d->tags.reserve(tagList.size());
    for (const QByteArray& ba : qAsConst(tagList)) {
        d->tags << QString::fromUtf8(ba.mid(4));
    }

    emitResult();
}

QStringList TagListJob::tags()
{
    return d->tags;
}
