package org.apache.slide.webdav.util.properties;

import java.util.Set;

import org.apache.slide.util.XMLValue;
import org.jdom.Element;
import org.jdom.JDOMException;

/**
 * Abstract {@link PropertyValueValidator} for properties that allow a fixed
 * set of XML-Elements as its values.
 */
public abstract class AbstractOptionValidator implements PropertyValueValidator
{

    protected abstract Set getAllowedValues();
    protected abstract boolean allowsEmptyValue();
    protected String getValueNamespace() {
        return "DAV:";
    }

    public void checkPropertyValue(Object value)
            throws InvalidLivePropertyValueException
    {
        if (value == null) {
            throw new InvalidLivePropertyValueException();
        }

        if (value.equals("")) {
            if (this.allowsEmptyValue()) {
                return;
            } else {
                throw new InvalidLivePropertyValueException();
            }
        }
            

        XMLValue xmlValue = null;
        if (value instanceof XMLValue) {
            xmlValue = (XMLValue)value;
        } else {
            try {
                xmlValue = new XMLValue(value.toString());
            } catch (JDOMException e) {
                throw new InvalidLivePropertyValueException();
            }
        }
        if (xmlValue.size() == 1) {
            Object o = xmlValue.getList().get(0);
            if (o instanceof Element ) {
	            String name = ((Element)o).getName();
	            String namespace = ((Element)xmlValue.getList().get(0)).getNamespaceURI();
	            if (namespace.equals(getValueNamespace()) && getAllowedValues().contains(name)) {
	                return; // OK
	            }
            }
        }
        throw new InvalidLivePropertyValueException();
    }
}