package be.iminds.ilabt.jfed.groovy_dsl.helpers;

import be.iminds.ilabt.jfed.groovy_dsl.DSLEventWriter;
import be.iminds.ilabt.jfed.groovy_dsl.DSLStreamException;
import be.iminds.ilabt.jfed.groovy_dsl.events.ClosureEndElement;
import be.iminds.ilabt.jfed.groovy_dsl.events.ClosureStartElement;
import be.iminds.ilabt.jfed.groovy_dsl.events.DSLEvent;
import be.iminds.ilabt.jfed.groovy_dsl.impl.events.DSLEventImpl;

import java.io.IOException;
import java.io.Writer;

/**
 * User: twalcari
 * Date: 5/18/2015
 * Time: 10:57
 */
public class IndentingDSLEventWriter extends DSLEventWriterDelegate {

    private int currentDepth = 0;

    public IndentingDSLEventWriter(DSLEventWriter out) {
        super(out);
    }

    @Override
    public void add(DSLEvent event) throws DSLStreamException {


        if (event instanceof ClosureEndElement) {
            currentDepth--;
        }

        StringBuilder spaces = new StringBuilder("");
        for (int i = 0; i < currentDepth; i++)
            spaces.append("\t");

        super.add(new CharactersEvent(spaces.toString()));

        super.add(event);

        if (event instanceof ClosureStartElement) {
            currentDepth++;
        }


    }

    private static class CharactersEvent extends DSLEventImpl {

        private final String data;

        private CharactersEvent(String data) {
            this.data = data;
        }

        public String getData() {
            return data;
        }

        @Override
        public void write(Writer writer) throws DSLStreamException {
            try {
                writer.write(data);
            } catch (IOException e) {
                throw new DSLStreamException(e);
            }
        }
    }
}
