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

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.apache.slide.common.PropertyName;
import org.apache.slide.util.conf.Configuration;
import org.apache.slide.util.conf.ConfigurationException;

/**
 * @author stefan
 */
public class DateValueValidator implements ConfigurablePropertyValueValidator {
    
    private PropertyName propertyName; 
    
    private static final SimpleDateFormat formats[] = {
            new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US),
            new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US),
            new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US),
            new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US),
            new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
        };

    public void setPropertyName(PropertyName propertyName) {
        this.propertyName = propertyName;
    }

    public PropertyName getPropertyName() {
        return this.propertyName;
    }

    public void checkPropertyValue(Object value)
            throws InvalidLivePropertyValueException {
        
        if (value == null) {
            throw new InvalidLivePropertyValueException();
        }
        if (value instanceof Date) {
            return;
        }
        String date = value.toString();
        for(int i = 0, l = formats.length; i < l; i++) {
            synchronized(formats[i]) {
                try {
                    formats[i].parse(date);
                    return; // fine, we have found a matching format
                }
                catch (ParseException e) {
                    // ignore, try next
                }
            }
        }
        // no format matches
        throw new InvalidLivePropertyValueException();
    }

    public void configure(Configuration configuration)
            throws ConfigurationException {
        // do nothing
    }
}
