package org.geotools.filter.v2_0.bindings;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import javax.xml.namespace.QName;

import org.geotools.filter.v2_0.FES;
import org.geotools.xml.InstanceComponent;
import org.geotools.xml.SimpleBinding;
import org.geotools.xml.impl.DatatypeConverterImpl;
import org.opengis.filter.identity.Version;

/**
 * Binding for FES 2.0 {@code VersionType} mapping to {@link Version}
 * 
 */
public class VersionTypeBinding implements SimpleBinding {

    @Override
    public QName getTarget() {
        return FES.VersionType;
    }

    @Override
    public Class<?> getType() {
        return Version.class;
    }

    @Override
    public int getExecutionMode() {
        return OVERRIDE;
    }

    @Override
    public Object parse(InstanceComponent instance, Object value) throws Exception {
        final String content = (String) value;

        try {
            Version.Action versionAction = Version.Action.valueOf(content);
            return new Version(versionAction);
        } catch (IllegalArgumentException e) {
            try {
                Integer index = Integer.valueOf(content);
                return new Version(index);
            } catch (NumberFormatException nfe) {
                Calendar dateTime = DatatypeConverterImpl.getInstance().parseDateTime(content);
                return new Version(dateTime.getTime());
            }
        }
    }

    @Override
    public String encode(Object object, String value) throws Exception {
        Version version = (Version) object;
        if (version.getDateTime() != null) {
            Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"));
            cal.setTimeInMillis(version.getDateTime().getTime());
            String dateTime = DatatypeConverterImpl.getInstance().printDateTime(cal);
            return dateTime;
        }
        if (version.getIndex() != null) {
            return String.valueOf(version.getIndex());
        }
        if (version.getVersionAction() != null) {
            return String.valueOf(version.getVersionAction());
        }
        throw new IllegalArgumentException("Empty version union");
    }
}

@@ -1586,33 +1586,32 @@
 ject;%0A        if
- 
 (version.getDate
@@ -1607,31 +1607,87 @@
 ion.
-getDateTime() != null) 
+isEmpty())%7B%0A            return null;%0A        %7D%0A        if(version.isDateTime())
 %7B%0A  
@@ -1964,33 +1964,32 @@
     %7D%0A        if
- 
 (version.getInde
@@ -1985,28 +1985,18 @@
 ion.
-get
+is
 Index()
- != null) 
+)
 %7B%0A  
@@ -2068,17 +2068,16 @@
       if
- 
 (version
@@ -2069,35 +2069,34 @@
      if(version.
-get
+is
 VersionAction() 
@@ -2098,18 +2098,9 @@
 on()
- != null) 
+)
 %7B%0A  

fix encoding of version