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

#include "compositePattern.h"


#include <QStringMatcher>


class wordPattern : public compositePattern
{

public:
    enum Type {AllWords, AnyWord};

    wordPattern();
    wordPattern(const QString& pattern, const Type type, const Qt::CaseSensitivity cs);
    inline ~wordPattern() {}


    void setPattern(const QString& pattern, const Type type, const Qt::CaseSensitivity cs = Qt::CaseSensitive);

    inline bool matches(const QString& str) const
    {
        _matched_length = -1;
        if (str.length() == 0)
            return false;
        if (_type == AllWords)
        {
            for (int i = _subpattern_count - 1; i >= 0; --i)
                if (_submatchers.at(i).indexIn(str) == -1)
                    return false;
            return true;
        }
        else
        {
            for (int i = 0; i < _subpattern_count; ++i)
                if (_submatchers.at(i).indexIn(str) != -1)
                    return true;
            return false;
        }
    }
    inline int indexIn(const QString& str, const int from = 0) const
    {
        // Do not match. Get index for (w1|w2|...).
        _matched_length = -1;
        if (str.length() == 0)
            return -1;
        int index(str.length());
        for (int i = 0; i < _subpattern_count; ++i)
        {
            const int p(_submatchers.at(i).indexIn(str, from));
            if (p != -1 && p < index)
            {
                index = p;
                _matched_length = _substrings.at(i).length();
            }
        }
        if (index == str.length())
            index = -1;
        return index;
    }
    inline const QVector<QStringMatcher>& submatchers() const
    {
        return _submatchers;
    }


private:
    QVector<QStringMatcher> _submatchers;
    Type _type;

};

#endif
