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.xmlio.out.XMLStringWriter;
import org.apache.commons.xmlio.out.XMLWriter;
import org.apache.slide.projector.value.MessageValue;
import org.jdom.Element;

public class MessageFactory extends AbstractValueFactory {
	public final static String ID = "id";
	public final static String ARGUMENTS = "arguments";

	public Class getValueClass() {
		return MessageValue.class;
	}
	
	public String getElementName() {
    	return "message";
    }
    
	public Object load(Element element) {
		String messageId = element.getAttributeValue(ID);
		List children = new ArrayList();
		for ( Iterator i = element.getChildren().iterator(); i.hasNext(); ) {
			Element childElement = (Element)i.next();
			children.add(ConstraintsManager.getInstance().loadValue(childElement));			
		}
		return new MessageValue(messageId, children.toArray());
	}

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

    public Constraints loadDescriptor(Element element) {
    	return new MessageConstraints();
    }
}