/*****************************************************************************
 * $CAMITK_LICENCE_BEGIN$
 *
 * CamiTK - Computer Assisted Medical Intervention ToolKit
 * (c) 2001-2025 Univ. Grenoble Alpes, CNRS, Grenoble INP - UGA, TIMC, 38000 Grenoble, France
 *
 * Visit http://camitk.imag.fr for more information
 *
 * This file is part of CamiTK.
 *
 * CamiTK is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * CamiTK is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with CamiTK.  If not, see <http://www.gnu.org/licenses/>.
 *
 * $CAMITK_LICENCE_END$
 ****************************************************************************/

#include "SyntaxHighlighter.h"

using namespace camitk;

// -------------------- Constructor --------------------
SyntaxHighlighter::SyntaxHighlighter(QTextDocument* parent) : QSyntaxHighlighter(parent) {
    monospaceFont.setFamily("Monospace");
    monospaceFont.setStyleHint(QFont::TypeWriter);
    monospaceFont.setFixedPitch(true);
}

// -------------------- addRule --------------------
void SyntaxHighlighter::addRule(QString regexp, QColor color, int weight, bool italic, QColor backgroundColor) {
    if (!rules.contains(regexp)) {
        QTextCharFormat format;
        format.setFont(monospaceFont); // force monospace
        format.setForeground(color);
        format.setFontWeight(weight);
        format.setFontItalic(italic);
        if (backgroundColor != Qt::transparent) {
            format.setBackground(backgroundColor);
        }
        rules.insert(regexp, QRegularExpression(regexp));
        formatters.insert(regexp, format);
    }
}

// -------------------- removeRule --------------------
bool SyntaxHighlighter::removeRule(QString regexp) {
    if (rules.remove(regexp) > 0) {
        return (formatters.remove(regexp) > 0);
    }
    else {
        return false;
    }
}

// -------------------- highlightBlock --------------------
void SyntaxHighlighter::highlightBlock(const QString& text) {
    //-- go through each rules
    for (auto rule : rules.keys()) {
        highlightPattern(text, rule);
    }
}

// -------------------- highlightPattern --------------------
void SyntaxHighlighter::highlightPattern(const QString& text, const QString& pattern) {
    QRegularExpressionMatchIterator matchIterator = rules.value(pattern).globalMatch(text);
    // QTextFormat format = ;
    while (matchIterator.hasNext()) {
        QRegularExpressionMatch match = matchIterator.next();
        setFormat(match.capturedStart(), match.capturedLength(), formatters.value(pattern));
    }
}