package be.iminds.ilabt.jfed.groovy_dsl.impl.events;

import be.iminds.ilabt.jfed.groovy_dsl.DSLStreamException;
import be.iminds.ilabt.jfed.groovy_dsl.events.FunctionArgument;
import be.iminds.ilabt.jfed.groovy_dsl.events.FunctionCallElement;

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

/**
 * User: twalcari
 * Date: 5/18/2015
 * Time: 16:36
 */
public class FunctionCallElementImpl extends DSLEventImpl implements FunctionCallElement {

    private final String name;
    private final FunctionArgument[] arguments;

    public FunctionCallElementImpl(String name, FunctionArgument... arguments) {
        this.name = name;
        this.arguments = arguments;
    }

    @Override
    public void write(Writer writer) throws DSLStreamException {
        try {
            writer.write(name);
            writer.write(" ");

            for (int i = 0; i < arguments.length - 1; i++) {
                writeArgument(arguments[i], writer);
                writer.write(", ");
            }
            if (arguments.length >= 0)
                writeArgument(arguments[arguments.length - 1], writer);

            writer.write("\n");
        } catch (IOException ex) {
            throw new DSLStreamException(ex);
        }
    }

    private void writeArgument(FunctionArgument argument, Writer writer) throws DSLStreamException {
        assert (argument instanceof FunctionArgumentImpl);

        ((FunctionArgumentImpl) argument).write(writer);
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public FunctionArgument[] getArguments() {
        return arguments;
    }
}
