package org.apache.slide.projector.constraints;

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

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

public class ListFactory extends AbstractValueFactory {
	public Class getValueClass() {
		return List.class;
	}
	
	public String getElementName() {
    	return "list";
    }
    
	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;
	}

    public void save(Object value, XMLStringWriter writer) {
    	writer.writeStartTag(XMLWriter.createStartTag(getElementName()));
        for ( Iterator i = ((List)value).iterator(); i.hasNext(); ) {
            ConstraintsManager.getInstance().saveValue(i.next(), 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 ListConstraints(allowedArrayValue);
        }
        return new ListConstraints();
    }
}