/***************************************************************************
 *   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 C2BBIBSEARCHER_H
#define C2BBIBSEARCHER_H

#include "c2bBibSearcherCache.h"
#include "c2bSearchPattern.h"

#include <QMap>
#include <QObject>
#include <QStringList>


class bibReference;
class c2bBibParser;

class c2bBibSearcher : public QObject
{

    Q_OBJECT

public:
    c2bBibSearcher(QObject* parento = 0);
    ~c2bBibSearcher();

    const QString highlight(const QString& abstract);
    QMap<QString, QString> hitMap;
    QString hitString;
    QString logString;
    void addPattern(bool Not, bool caseSensitive, const QString& patternType, const QString& scope,
                    const QString& yearScope, const QString& pattern);
    void exec();

    inline void setBoolean(bool And)
    {
        p_boolean_and = And;
    }

    inline void setScope(const QString& file, const QString& dir, bool all, bool includePdf)
    {
        clear();
        p_bibtex_file = file;
        p_bibtex_dir = dir;
        p_all_bibtex_files = all;
        p_include_pdf = includePdf;
    }

    inline void setSimplifySource(bool simplify)
    {
        p_simplify_source = simplify;
    }

    inline int errorCount() const
    {
        return errorCounter;
    }

    inline int hitCount() const
    {
        return hitMap.count();
    }

    inline int patternCount() const
    {
        return patternList.count();
    }

    inline int referenceCount() const
    {
        return referenceCounter;
    }


public slots:
    void abort();


private:
    QList<c2bSearchPattern> patternList;
    QString p_bibtex_dir;
    QString p_bibtex_file;
    QStringList fieldList;
    bool p_aborted;
    bool p_all_bibtex_files;
    bool p_boolean_and;
    bool p_include_pdf;
    bool p_simplify_source;
    c2bBibParser* bp;
    c2bBibSearcherCache cache;
    const QString excerpts(const QString& contents);
    const QString location(const QString& fn, const bibReference& ref);
    int bibtexCounter;
    int errorCounter;
    int pdfCounter;
    int referenceCounter;
    void clear();
    void search(const QString& bib_file);
    void searchBib(const QString& bib_file, const bibReference& ref);

    inline bool include_pdf(bool include, const QString& file_name, QString* file_contents)
    {
        if (!include)
            return false;
        if (*file_contents == "unread")
            *file_contents = cache.pdfToText(file_name, &pdfCounter, &logString, &errorCounter);
        return !(file_contents->isEmpty());
    }

};

#endif
