/*
 * $Header: /home/cvspublic/jakarta-slide/projector/src/java/org/apache/slide/projector/constraints/ConstraintsManager.java,v 1.2 2004/11/28 13:54:05 dflorey Exp $
 * $Revision: 1.2 $
 * $Date: 2004/11/28 13:54:05 $
 *
 * ====================================================================
 *
 * Copyright 2004 The Apache Software Foundation 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package org.apache.slide.projector.constraints;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

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

/**
 * The AdapterManager
 * 
 */
public class ConstraintsManager {
	private final static ConstraintsManager valueDescriptorManager = new ConstraintsManager();
	private Map registeredFactories = new HashMap();
	
	public static ConstraintsManager getInstance() {
		return valueDescriptorManager;
	}
	
    public String getContentType(Object object) {
        ConstraintsFactory factory = (ConstraintsFactory)registeredFactories.get(object.getClass().getName());
        if ( factory != null ) return factory.getContentType(object);
        return object.getClass().getName();
    }
    
	public void registerDescriptorFactory(ConstraintsFactory factory) {
		registeredFactories.put(factory.getValueClass().getName(), factory);
	}
    
	public Constraints loadConstraints(Element element) {
        ConstraintsFactory factory = getFactoryByElement(element);
        return factory != null ? factory.loadDescriptor(element) : null;
	}
	
	public Object loadValue(Element element) {
        ConstraintsFactory factory = getFactoryByElement(element);
        return factory != null ? factory.load(element) : null;
	}
	
	public void saveValue(Object value, XMLStringWriter xmlStringWriter) {
        ConstraintsFactory factory = (ConstraintsFactory)registeredFactories.get(value.getClass().getName());
        if ( factory != null ) factory.save(value, xmlStringWriter);
	}
    
    private ConstraintsFactory getFactoryByElement(Element element) {
        for ( Iterator i = registeredFactories.values().iterator(); i.hasNext(); ) {
            ConstraintsFactory factory = (ConstraintsFactory)i.next();
            if ( element.getName().equals(factory.getElementName()) ) {
                return factory;  
            }
        }
        return null;
    }
}