/***************************************************************************
 *   Copyright (C) 2004-2009 by Pere Constans
 *   constans@molspaces.com
 *   cb2Bib version 1.3.2. Licensed under the GNU GPL version 3.
 *   See the LICENSE file that comes with this distribution.
 ***************************************************************************/
#ifndef C2BSEARCHPATTERN_H
#define C2BSEARCHPATTERN_H

#include <QRegExp>
#include <QList>


class c2bSearchPattern
{

public:
    c2bSearchPattern(const QString& newPattern, const QString& newPatternType);
    c2bSearchPattern(bool newNot, bool newCaseSensitive, const QString& newPatternType, const QString& newScope,
                     const QString& newYearScope, const QString& newPattern);

    QList<QRegExp> subrx;
    QRegExp rx;
    QString pattern;
    QString scope;
    QString yearScope;
    bool Not;

    inline bool matches(const QString& contents) const
    {
        if (subrx.count() > 0)
        {
            // Decompose pattern to scan long strings.
            // Decomposing improves efficiency over a factor of two.
            // Probability sorted subpatterns improves an additional ~15%.
            if (_match_any_subpattern)
            {
                for (int i = 0; i < subrx.count(); ++i)
                    if (contents.contains(subrx.at(i)))
                        return true;
                return false;
            }
            else
            {
                for (int i = subrx.count() - 1; i >= 0; --i)
                    if (!contents.contains(subrx.at(i)))
                        return false;
                return true;
            }
        }
        else
            return contents.contains(rx);
    }

    inline const QString toString() const
    {
        return _pattern_string;
    }

    inline bool operator< (const c2bSearchPattern& p) const
    {
        return (_rank < p._rank);
    }


private:
    QString _pattern_string;
    bool _match_any_subpattern;
    int _rank;
    void initType(const QString& type);

};

#endif
