/***************************** 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 *************************************/

#include "TreeModelMatchCollector.h"

#include <QtGlobal>
#include <QAbstractItemModel>
#include <QDebug>

void TreeModelMatchCollector::setModel(QAbstractItemModel* model)
{
    model_ = model;
}

bool TreeModelMatchCollector::isSameAsStartIndex(const QModelIndex& idx) const
{
    return idx.row() == startIndex_.row() && idx.parent() == startIndex_.parent();
}

void TreeModelMatchCollector::clear()
{
    startIndex_ = QModelIndex();
    startItemPos_ = -1;
    startItemFound_ = false;
    startIndexPassed_ = false;
    value_.clear();
    columns_.clear();
    flags_ = Qt::MatchRecursive;
    items_.clear();
}

void TreeModelMatchCollector::match(QString value, QVector<int> columns, Qt::MatchFlags flags,
                                    const QModelIndex& startIndex)
{
    if (!model_)
        clear();

    if (value_ == value && columns_ == columns && flags_ == flags)
        return;

    startIndex_ = startIndex;
    startItemPos_ = -1;
    startItemFound_ = false;
    startIndexPassed_ = false;

    value_ = value;
    columns_ = columns;
    flags_ = flags;
    items_.clear();

    buildRx();

    for (int i = 0; i < model_->rowCount(); i++) {
        findMatch(i, QModelIndex());
    }

    if (startItemPos_ == -1 && items_.count() > 0)
        startItemPos_ = 0;
}

void TreeModelMatchCollector::buildRx()
{
    if (flags_.testFlag(Qt::MatchWildcard)) {
#if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)
        wildcardRx_ = QRegularExpression();
        wildcardRx_.setPattern(QRegularExpression::wildcardToRegularExpression(value_));
        if (!flags_.testFlag(Qt::MatchCaseSensitive))
            wildcardRx_.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
#else
        wildcardRx_ = QRegExp(value_);
        wildcardRx_.setPatternSyntax(QRegExp::Wildcard);
        Qt::CaseSensitivity cs = (flags_.testFlag(Qt::MatchCaseSensitive)) ? Qt::CaseSensitive : Qt::CaseInsensitive;
        wildcardRx_.setCaseSensitivity(cs);
#endif
    }
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
    else if (flags_.testFlag(Qt::MatchRegularExpression)) {
#else
    else if (flags_.testFlag(Qt::MatchRegExp)) {
#endif
        rx_ = QRegularExpression(value_);
        if (!flags_.testFlag(Qt::MatchCaseSensitive))
            rx_.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
    }
}

void TreeModelMatchCollector::findMatch(int row, const QModelIndex& parentIdx)
{
    bool found = false;
    for (auto column : columns_) {
        auto idx = model_->index(row, column, parentIdx);
        QString s = idx.data(Qt::DisplayRole).toString();
        if (flags_.testFlag(Qt::MatchWildcard)) {
            if (s.contains(wildcardRx_)) {
                found = true;
                break;
            }
        }
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
        else if (flags_.testFlag(Qt::MatchRegularExpression)) {
#else
        else if (flags_.testFlag(Qt::MatchRegExp)) {
#endif
            if (s.contains(rx_)) {
                found = true;
                break;
            }
        }
        else {
            if (s.contains(value_,
                           (flags_.testFlag(Qt::MatchCaseSensitive)) ? Qt::CaseSensitive : Qt::CaseInsensitive)) {
                found = true;
                break;
            }
        }
    }

    auto refIdx = model_->index(row, 0, parentIdx);

    if (found) {
        items_ << refIdx;
    }

    if (refIdx == startIndex_) {
        startItemPos_ = items_.count() - 1;
        startIndexPassed_ = true;
        if (found)
            startItemFound_ = true;
    }
    else if (startIndexPassed_ && !startItemFound_ && found) {
        startItemPos_ = items_.count() - 1;
        startItemFound_ = true;
    }

    int chNum = model_->rowCount(refIdx);
    for (int i = 0; i < chNum; i++) {
        findMatch(i, refIdx);
    }
}

void TreeModelMatchCollector::allValues(QSet<QString>& vals) const
{
    for (int i = 0; i < model_->rowCount(); i++)
        allValues(i, QModelIndex(), vals);
}

void TreeModelMatchCollector::allValues(int row, const QModelIndex& parentIdx, QSet<QString>& vals) const
{
    for (auto column : columns_) {
        auto idx = model_->index(row, column, parentIdx);
        vals << idx.data(Qt::DisplayRole).toString();
    }

    auto refIdx = model_->index(row, 0, parentIdx);
    int chNum = model_->rowCount(refIdx);
    for (int i = 0; i < chNum; i++)
        allValues(i, refIdx, vals);
}
