package org.apache.slide.projector.constraints;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.contract.constraints.Constraints;
import org.apache.commons.contract.constraints.NumberConstraints;
import org.apache.commons.xmlio.in.ConversionHelpers;
import org.jdom.Element;

public class NumberFactory extends AbstractValueFactory {
    public final static String CONTENT_TYPE = "projector/number";
    
	public Class getValueClass() {
		return Number.class;
	}
	
	public String getElementName() {
    	return "number";
    }

    public Object load(Element element) {
		return new BigDecimal(element.getText());
	}
    
    public Constraints loadDescriptor(Element element) {
    	NumberConstraints valueDescriptor = new NumberConstraints();
        String mininum = element.getAttributeValue("minimum");
        String maximum = element.getAttributeValue("maximum");
        if ( mininum != null ) valueDescriptor.setMinimum(new BigDecimal(mininum));
        if ( maximum != null ) valueDescriptor.setMaximum(new BigDecimal(maximum));
    	List allowedValueElements = element.getChildren("allowed-value");
    	for ( Iterator i = allowedValueElements.iterator(); i.hasNext(); ) {
    		Element allowedValueElement = (Element)i.next(); 
            boolean isDefault = ConversionHelpers.getBoolean(allowedValueElement.getAttributeValue("default"), false);
            Number allowedValue = new BigDecimal(allowedValueElement.getTextTrim()); 
            valueDescriptor.addAllowedValue(allowedValue);
    	}
    	return valueDescriptor;
    }
}