package org.treesched.ant;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DynamicConfigurator;
import org.treesched.Schedule;
import org.treesched.ScheduleFactory;
import org.treesched.ScheduleList;

/**
 * When configuring a {@link org.treesched.CompoundSchedule} in
 * an Ant build file it's necessary to have this Element class
 * to set properties of the on of the schedules of the parent.
 * 
 * @see org.treesched.schedules.BrokenSchedule
 * 
 * @author Rob Gordon.
 */

public class CompoundScheduleProxy implements DynamicConfigurator {

    /** The parent compound schedule */
	private final Schedule schedule;
	private final ScheduleList children = new ScheduleList();
	
	/**
	 * Constructor. 
	 * 
	 * @param schedule The parent schedule we're setting 
	 * properties on.
	 * @param name The name of the element which contains 
	 * the schedule.
	 */
	public CompoundScheduleProxy(Schedule schedule, String name) {
		this.schedule = schedule;
	    String mName = "set" + NestedScheduleElement.capitalize(name);
	    try {
		    Method setter= schedule.getClass().getMethod(mName, new Class[] {Schedule.class} );
            setter.invoke(schedule, new Object[] {children});
        } catch (IllegalArgumentException e) {
			throw new BuildException("Failed to set attribute " + name, e);
        } catch (NoSuchMethodException e) {
			throw new BuildException("Failed to set attribute " + name, e);
        } catch (IllegalAccessException e) {
			throw new BuildException("Failed to set attribute " + name, e);
        } catch (InvocationTargetException e) {
			throw new BuildException("Failed to set attribute " + name, e);
        }
	}
	
	/* (non-Javadoc)
	 * @see org.apache.ant.DynamicConfigurator#setDynamicAttribute(java.lang.String, java.lang.Object)
	 */
	public void setDynamicAttribute(String name, String value)
	throws BuildException {
	    throw new BuildException("Unsupported attribute " + name);
	}
	/* (non-Javadoc)
	 * @see org.oddjob.arooa.DynamicConfigurator#createDynamicElement(java.lang.String)
	 */
	public Object createDynamicElement(String name) throws BuildException {

		ScheduleFactory factory = ScheduleFactory.getInstance();
		Schedule newChild = factory.createSchedule(name);
		
		children.addChildSchedule(newChild);
		NestedScheduleElement se = new NestedScheduleElement(newChild);
		return se;
	}
}
