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

#include <QVector>

#ifdef C2B_DEBUG_SEARCHING
#include <QtDebug>
#endif


struct scorer
{
    scorer() : memweight(0.9), memstarts(300), memends(2300), tscore(0), mscore(0), nscores(0), mempos(-1) {}


    void setPattern(const QVector<int>& patternlengths)
    {
        plengths = patternlengths;
    }
    void setPattern(const int length)
    {
        plengths.clear();
        if (length > 0)
            plengths.append(length);
    }
    void initialize()
    {
        tscore = double(0);
        mscore = double(0);
        nscores = 0;
        mempos = -1;
    }
    void update(const int pos, const int mlength)
    {
        ++nscores;

        if (plengths.count() == 0)
        {
            // FixedStringAllWords and FixedStringAnyWord cases
            tscore += double(1);
            return;
        }

        // Combine the two parallel processes (P. Constans. Relevance ranking for online text matching. 2021):
        //  - working memory in tscore
        //  - refreshing activation in mscore
        if (plengths.contains(mlength))
        {
            tscore += double(1);
            if (mempos >= 0 && pos >= mempos + memstarts && pos <= mempos + memends)
                mscore += double(1);
            mempos = pos;
        }
        else
            tscore += localScore(mlength);
    }
    double localScore(const int mlength) const
    {
        double ls(0);
        for (int i = 0; i < plengths.count(); ++i)
            ls = std::max(ls, double(std::min(plengths.at(i), mlength)) / double(std::max(plengths.at(i), mlength)));
        return ls;
    }
    double score() const
    {
#ifdef C2B_DEBUG_SEARCHING
        qDebug() << "scorer: n tscore mscore  score" << nscores << tscore << mscore << "  "
                 << (double(1) - memweight) * tscore + memweight* mscore;
#endif
        return (double(1) - memweight) * tscore + memweight * mscore;
    }

    double memweight;
    int memstarts, memends;

    double tscore, mscore;
    int nscores, mempos;

    QVector<int> plengths;
};

#endif
