#include "Query.hh"

QString generateQuery(QString const &base, QString const &attribute, QString const &value)
{
    QString condition = QString("@%1=\"%2\"").arg(attribute).arg(value);
    
    return generateQuery(base, condition);
}

QString generateQuery(QString const &base, QString const &condition)
{
    int subSelectionPos = base.lastIndexOf('/');
    
    if (!subSelectionPos)
        return QString();
    
    int closingBracketPos = base.mid(subSelectionPos).lastIndexOf(']');
    
    if (closingBracketPos == -1)
        return QString("%1[%2]").arg(base).arg(condition);
    else
        return QString("%1 and %2%3").arg(
            base.left(subSelectionPos + closingBracketPos),
            condition,
            base.mid(subSelectionPos + closingBracketPos));
}

#include <QtDebug>

#include "Query.hh"

QString generateQuery(QString const &base, QString const &attribute, QString const &value)
{
    QString condition = QString("@%1=\"%2\"").arg(attribute).arg(value);
    
    return generateQuery(base, condition);
}

QString generateQuery(QString const &base, QString const &condition)
{
    int subSelectionPos = base.lastIndexOf('/');
    
    if (!subSelectionPos)
        return QString();
   
    int openingBracketPos = base.indexOf('[', subSelectionPos);
    
    if (openingBracketPos == -1)
        return QString("%1[%2]").arg(base).arg(condition);

    // Add parenthesis around original predicates.
    QString expanded = base;
    expanded.insert(openingBracketPos + 1, '(');

    int closingBracketPos = expanded.lastIndexOf(']');
    if (closingBracketPos == -1) {
      qDebug() << "Malformed query?: " << base;
      return base;
    }

    expanded.insert(closingBracketPos, QString(") and %1").arg(condition));
    
    return expanded;
}

Add parenthesis around predicates before query expansion.
Add parenthesis around predicates before query expansion.

The query expansion gives incorrect results when the predicate
is a disjunction (#132). E.g.:

//node[@word="bezorgd" or @word="bezorgde"]

was incorrectly expanded to:

//node[@word="bezorgd" or @word="bezorgde" and CONDITION]

rather than the correct

//node[(@word="bezorgd" or @word="bezorgde") and CONDITION]

Ideally we should do this using AST manipulation. Though it
seems that XQilla does not provide any obvious way to serialize
an expression AST to a query string. So, we proceed doing this
the ugly way.

Fixes #132.
