package metalexer.jflex;

import java.io.PrintWriter;

public class PrintHelper {
    private final PrintWriter out;
    private final String singleIndentString;

    private int indentLevel;
    private boolean requireIndent;
    private String indentString;

    public PrintHelper(PrintWriter out, int indentSize) {
        this.out = out;

        StringBuffer buf = new StringBuffer();
        for(int i = 0; i < indentSize; i++) {
            buf.append(' ');
        }
        this.singleIndentString = buf.toString();

        this.indentLevel = 0;
        this.requireIndent = true; //doesn't actually matter, but conceptually true
        updateIndentString();
    }

    public void print(String msg) {
        maybePrintIndent();
        out.print(msg);
    }

    public void println(String msg) {
        maybePrintIndent();
        out.println(msg);
        requireIndent = true;
    }

    public void println() {
        maybePrintIndent();
        out.println();
        requireIndent = true;
    }

    public void close() {
        out.close();
    }

    public void indent() {
        indentLevel++;
        updateIndentString();
    }

    public void dedent() {
        indentLevel--;
        updateIndentString();
    }

    private void updateIndentString() {
        StringBuffer buf = new StringBuffer();
        for(int i = 0; i < indentLevel; i++) {
            buf.append(singleIndentString);
        }
        indentString = buf.toString();
    }

    private void maybePrintIndent() {
        if(requireIndent) {
            out.print(indentString);
            requireIndent = false;
        }
    }
}
