package org.apache.slide.projector.constraints;

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

import org.apache.commons.contract.Context;
import org.apache.commons.contract.constraints.CastException;
import org.apache.commons.contract.constraints.Constraints;
import org.apache.commons.contract.constraints.ValidationException;
import org.apache.commons.i18n.LocalizedError;
import org.apache.commons.i18n.LocalizedText;
import org.apache.slide.projector.ContentType;

public class AnyConstraints implements Constraints {
    public static final AnyConstraints UNCONSTRAINED = new AnyConstraints();

    protected List allowedContentTypes = new ArrayList();
    private boolean constrained = false;

    public AnyConstraints() {
    }

    public AnyConstraints(String allowedContentType) {
        allowedContentTypes.add(allowedContentType);
        constrained = true;
    }

    public void addAllowedContentType(String allowedContentType) {
        allowedContentTypes.add(allowedContentType);
        constrained = true;
    }

    public String[] getAllowedContentTypes() {
        return (String [])allowedContentTypes.toArray(new String[0]);
    }

    public Object cast(Object value, Context context) throws CastException {
        if ( value instanceof String[] ) {
            return ((String [])value)[0];
        } else {
            return value; 
        }
    }
    
    public void validate(Object value, Context context) throws ValidationException {
         if ( constrained ) {
            for ( Iterator i = allowedContentTypes.iterator(); i.hasNext(); ) {
                if ( ContentType.matches((String)i.next(), ConstraintsManager.getInstance().getContentType(value))) {
                    return;
                }
            }
            throw new ValidationException(new LocalizedError("invalidValue", new String[] { ConstraintsManager.getInstance().getContentType(value), ContentType.getContentTypesAsString(allowedContentTypes) }));
        }
    }

    public LocalizedText verboseConstraints() {
        // TODO Auto-generated method stub
        return null;
    }
}