package net.ranides.assira.grammar;

import lombok.experimental.UtilityClass;
import net.ranides.assira.text.StrAppender;
import net.ranides.assira.text.StrBuilder;

@UtilityClass
public class G4Support {

    public static String printTree(G4Node node) {
        return printTree(new StrBuilder(), node).toString();
    }

    public static <T extends Appendable> T printTree(T output, G4Node node) {
        printTree0(new StrAppender(output), "", node);
        return output;
    }

    private static <T extends Appendable> void printTree0(StrAppender output, String indent, G4Node node) {
        output.append(indent).printf("%s = '%s'", node.name(), node.text()).endl();
        node.children().forEach(n -> {
            printTree0(output, indent+"   ", n);
        });
    }

    public static String printPath(G4Node node) {
        return printPath(new StrBuilder(), node).toString();
    }

    public static <T extends Appendable> T printPath(T output, G4Node node) {
        printPath0(new StrAppender(output), node);
        return output;
    }

    private static void printPath0(StrAppender output, G4Node node) {
        output.printf("%s = '%s'", node.path(), node.text()).endl();
        node.children().forEach(n -> {
            printPath0(output, n);
        });
    }

}
