/* FichothequeLib_Tools - Copyright (c) 2023 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package net.fichotheque.tools.extraction.syntaxes;

import java.io.IOException;
import net.fichotheque.utils.SyntaxUtils;
import net.mapeadores.util.exceptions.ShouldNotOccurException;


/**
 *
 * @author Vincent Calame
 */
public abstract class AbstractStepResolver {

    private final StringBuilder finalBuf = new StringBuilder();
    private StringBuilder currentBuf = new StringBuilder();

    public AbstractStepResolver() {

    }

    public void resolveText(String text) {
        int length = text.length();
        for (int i = 0; i < length; i++) {
            resolveChar(text.charAt(i));
        }
        flush(true);
    }

    protected void appendSpaceToFinal() {
        finalBuf.append(' ');
    }

    protected void appendToFinal(String className, String textPart) {
        try {
            if (className != null) {
                SyntaxUtils.appendSpan(finalBuf, className, textPart);
            } else {
                SyntaxUtils.escape(finalBuf, textPart);
            }
        } catch (IOException ioe) {
            throw new ShouldNotOccurException();
        }
    }

    protected void appendOperator(String textPart) {
        appendToFinal("cm-operator", textPart);
    }

    protected void appendPunctuation(String textPart) {
        appendToFinal("cm-punctuation", textPart);
    }

    protected void appendBracket(String textPart) {
        appendToFinal("cm-bracket", textPart);
    }

    protected void appendToCurrent(char carac) {
        currentBuf.append(carac);
    }

    protected void appendToCurrent(String part) {
        currentBuf.append(part);
    }

    protected void flush() {
        flush(false);
    }

    protected void flush(boolean lastPart) {
        if (currentBuf.length() == 0) {
            return;
        }
        String textPart = currentBuf.toString();
        appendToFinal(getStepClassName(textPart, lastPart), textPart);
        currentBuf = new StringBuilder();
    }

    public String end() {
        return finalBuf.toString();
    }

    public abstract void resolveChar(char carac);

    public abstract String getStepClassName(String textPart, boolean lastPart);

}
