package org.apache.slide.projector.constraints;

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

import org.apache.commons.contract.constraints.Constraints;
import org.apache.commons.contract.constraints.StringConstraints;
import org.apache.commons.xmlio.in.ConversionHelpers;
import org.apache.slide.projector.ContentType;
import org.jdom.Element;

public class StringFactory extends AbstractValueFactory {
	public Class getValueClass() {
		return String.class;
	}
	
	public String getElementName() {
    	return "string";
    }
    
	public Object load(Element element) {
		return element.getText();
	}
	
	public Constraints loadDescriptor(Element element) {
    	StringConstraints valueDescriptor = new StringConstraints();
        String mininum = element.getAttributeValue("minimum-length");
        String maximum = element.getAttributeValue("maximum-length");
        if ( mininum != null ) valueDescriptor.setMinimumLength(Integer.parseInt(mininum));
        if ( maximum != null ) valueDescriptor.setMaximumLength(Integer.parseInt(maximum));
    	List allowedStringElements = element.getChildren("allowed-value");
    	for ( Iterator i = allowedStringElements.iterator(); i.hasNext(); ) {
    		Element allowedStringElement = (Element)i.next(); 
            boolean isDefault = ConversionHelpers.getBoolean(allowedStringElement.getAttributeValue("default"), false);
            String allowedValue = allowedStringElement.getTextTrim(); 
            valueDescriptor.addAllowedValue(allowedValue);
    	}
    	return valueDescriptor;
    }

    public String getContentType(Object value) {
        return ContentType.PLAIN_TEXT;
    }

}