package org.apache.slide.projector.constraints;

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

import org.apache.commons.contract.constraints.ArrayConstraints;
import org.apache.commons.contract.constraints.Constraints;
import org.apache.commons.xmlio.out.XMLStringWriter;
import org.apache.commons.xmlio.out.XMLWriter;
import org.jdom.Element;

public class ArrayFactory extends AbstractValueFactory {
	public Class getValueClass() {
		return Object[].class;
	}
	
	public String getElementName() {
    	return "array";
    }
    
	public Object load(Element element) {
		List children = new ArrayList();
		for ( Iterator i = element.getChildren().iterator(); i.hasNext(); ) {
			Element childElement = (Element)i.next();
			children.add(ConstraintsManager.getInstance().loadValue(childElement));			
		}
		return children.toArray(new Object[children.size()]);
	}

    public void save(Object value, XMLStringWriter writer) {
    	Object[] array = (Object [])value;
    	writer.writeStartTag(XMLWriter.createStartTag(getElementName()));
        for ( int i = 0; i < array.length; i++ ) {
            ConstraintsManager.getInstance().saveValue(array[i], writer);
        }
        writer.writeEndTag(XMLWriter.createEndTag(getElementName()));
    }

    public Constraints loadDescriptor(Element element) {
    	Iterator childrenIterator = element.getChildren().iterator();;
        if ( childrenIterator.hasNext() ) {
            Constraints allowedArrayValue = ConstraintsManager.getInstance().loadConstraints((Element)childrenIterator.next());
            return new ArrayConstraints(allowedArrayValue);
        }
        return new ArrayConstraints();
    }
}