package org.apache.slide.projector.constraints;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

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.ElementValue;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class XMLFactory extends AbstractValueFactory {
    private final static XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
    private final static Logger logger = Logger.getLogger(XMLFactory.class.getName());
    
	public Class getValueClass() {
		return ElementValue.class;
	}
	
	public String getElementName() {
    	return "xml";
    }
    
    public Constraints loadDescriptor(Element element) {
    	AnyConstraints valueDescriptor = new AnyConstraints();
    	List allowedValueElements = element.getChildren("allowed-content-type");
    	for ( Iterator i = allowedValueElements.iterator(); i.hasNext(); ) {
    		Element allowedValueElement = (Element)i.next(); 
            String allowedValue = allowedValueElement.getTextTrim(); 
            valueDescriptor.addAllowedContentType(allowedValue);
    	}
    	return valueDescriptor;
    }

    public Object load(Element element) {
    	Iterator iterator = element.getChildren().iterator();
    	if ( iterator.hasNext() ) {
    		return new ElementValue((Element)iterator.next());
    	}
		return new ElementValue(element);
	}
    
    public void save(Object value, XMLStringWriter writer) {
    	ElementValue elementValue = (ElementValue)value;
    	try {
    		xmlOutputter.output(elementValue.getRootElement(), writer);
    	} catch (IOException e) {
    		logger.log(Level.SEVERE, "Could not persist ElementValue", e);
    	}
    	writer.writeEndTag(XMLWriter.createEndTag(getElementName()));
    }
}