package sharin.sql.formatter;

import java.util.ArrayList;
import java.util.List;

class BasicResultBuffer {

    private final List<StringBuilder> builderList = new ArrayList<StringBuilder>();

    private final StringBuilder result = new StringBuilder();

    public BasicResultBuffer() {
        builderList.add(null);
    }

    public void append(String s) {
        StringBuilder builder = null;
        int size = builderList.size();

        if (size >= 1) {
            builder = builderList.get(size - 1);
        }

        if (builder == null) {
            builder = result;
        }

        append(builder, s);
    }

    private void append(StringBuilder builder, String s) {

        if (s == null || s.length() == 0) {
            return;
        }

        if (builder.length() > 0) {
            builder.append(' ');
        }

        builder.append(s);
    }

    public void flush() {

        for (int i = 0; i < builderList.size(); i++) {
            StringBuilder builder = builderList.get(i);

            if (builder != null) {
                append(result, builder.toString());
                builderList.set(i, null);
            }
        }
    }

    public void begin() {
        builderList.add(new StringBuilder());
    }

    public void prepend(String s) {
        int size = builderList.size();

        if (size >= 2 && builderList.get(size - 2) == null) {
            append(s);
        }
    }

    public void end() {
        int size = builderList.size();

        if (size >= 1) {
            builderList.remove(size - 1);
        }
    }

    public String getResult() {
        return result.toString();
    }
}
