/* FichothequeLib_API - Copyright (c) 2025 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.syntax;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;


/**
 *
 * @author Vincent Calame
 */
public class FicheblockSyntaxHandler implements Appendable {

    private final StringBuilder buf;
    private final Map<String, Integer> matchingMap = new LinkedHashMap<String, Integer>();
    private int lastLineNumber = 1;
    private int lastLength = 0;

    public FicheblockSyntaxHandler(StringBuilder buf) {
        this.buf = buf;
    }

    public StringBuilder getStringBuilder() {
        return buf;
    }

    @Override
    public Appendable append(CharSequence csq) throws IOException {
        buf.append(csq);
        return this;
    }

    @Override
    public Appendable append(CharSequence csq, int start, int end) throws IOException {
        buf.append(csq, start, end);
        return this;
    }

    @Override
    public Appendable append(char c) throws IOException {
        buf.append(c);
        return this;
    }

    public Map<String, Integer> getMatchingMap() {
        return matchingMap;
    }

    public void storeLine(String positionPrefix, int position) {
        storeLine(positionPrefix + position);
    }

    public void storeLine(String position) {
        int currentLength = buf.length();
        for (int i = lastLength; i < currentLength; i++) {
            char carac = buf.charAt(i);
            if (carac == '\n') {
                lastLineNumber++;
            }
        }
        matchingMap.put(position, lastLineNumber);
        lastLength = currentLength;
    }


}
