/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#pragma once

#include <QModelIndex>
#include <QModelIndexList>
#include <QSet>
#include <QRegularExpression>
#if QT_VERSION < QT_VERSION_CHECK(5, 12, 0)
#include <QRegExp>
#endif

class QAbstractItemModel;

class TreeModelMatchCollector
{
public:
    TreeModelMatchCollector() = default;

    void match(QString value, QVector<int> columns, Qt::MatchFlags flags,
               const QModelIndex& startIndex);

    void setModel(QAbstractItemModel* model);
    void clear();
    QModelIndexList items() const { return items_; }
    int itemCount() const { return items_.count(); }
    int startItemPos() const { return startItemPos_; }
    bool isSameAsStartIndex(const QModelIndex&) const;
    void allValues(QSet<QString>& vals) const;

private:
    void buildRx();
    void findMatch(int row, const QModelIndex& parentIdx);
    void allValues(int row, const QModelIndex& parentIdx, QSet<QString>& vals) const;

    QAbstractItemModel* model_{nullptr};
    QString value_;
    QVector<int> columns_;
    Qt::MatchFlags flags_{Qt::MatchRecursive};
    QModelIndex startIndex_;
    int startItemPos_{-1};
    bool startItemFound_{false};
    bool startIndexPassed_{false};
    QModelIndexList items_;

    QRegularExpression rx_;
#if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)
    QRegularExpression wildcardRx_;
#else
    QRegExp wildcardRx_;
#endif
};
