#include "search.h"

#include <QMap>

#include "entry.h"

namespace Dtk
{
namespace Util
{

class SearchData
{
public:
    SearchData() {}

    QMap<QString, QList<Entry *>> entrys;
};


Search::Search()
{
    d = new SearchData;
}

void Search::addEntry(const QString &value, void *data)
{
    auto entry = new Entry(value, data);
    for (auto &key : entry->keys()) {
        if (!d->entrys.contains(key)) {
            d->entrys.insert(key, QList<Entry *>() << entry);
        } else {
            d->entrys[key].append(entry);
        }
    }
}

void Search::removeEntry( Entry *entry)
{
    for (auto &key : d->entrys.keys()) {
        d->entrys[key].removeAll(entry);
    }
}

QList<Entry *> Search::findEntry(const QString &findKey)
{
    QMap<Entry *, int> findEntrys;
    for (auto &key : d->entrys.keys()) {
        if (key.contains(findKey)) {
            for (auto entry : d->entrys.value(key)) {
                findEntrys.insert(entry, 0);
            }
        }
    }
    return findEntrys.keys();
}

QList<QString> Search::findEntryValue(const QString &findKey)
{
    QMap<QString, int> findValues;
    for (auto &key : d->entrys.keys()) {
        if (key.contains(findKey)) {
            for (auto entry : d->entrys.value(key)) {
                findValues.insert(entry->value(), 0);
            }
        }
    }
    return findValues.keys();
}

QList<void *> Search::findEntryData(const QString &findKey)
{
    QMap<void *, int> findDatas;
    for (auto &key : d->entrys.keys()) {
        if (key.contains(findKey)) {
            for (auto entry : d->entrys.value(key)) {
                findDatas.insert(entry->data(), 0);
            }
        }
    }
    return findDatas.keys();
}

}
}
