package org.geotools.data.wfs;

import java.net.URL;

import junit.framework.TestCase;

import org.geotools.data.DefaultQuery;
import org.geotools.data.FeatureReader;
import org.geotools.data.FeatureSource;
import org.geotools.data.Query;
import org.geotools.data.Transaction;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.filter.Filter;
import org.geotools.filter.FilterFactory;
import org.geotools.filter.FilterFactoryFinder;
import org.geotools.filter.FilterType;
import org.geotools.filter.GeometryFilter;

public class MapServerWFSStrategyOnlineTest extends TestCase {
    private static final String TYPE_NAME = "hospitals"; //$NON-NLS-1$

    private WFSDataStore ds;

    private int totalFeatures;

    protected void setUp() throws Exception {
        URL host=new URL("http://mapserver.refractions.net/cgi-bin/mapserv48?map=/home/www/mapserv/maps/victoria-wms.map&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetCapabilities");
        ds=new WFSDataStore(host, null, null, null, 10000, 100, true, true);
        assertTrue( ds.strategy instanceof MapServerWFSStrategy );
        FilterFactory fac=FilterFactoryFinder.createFilterFactory();
        
        GeometryFilter filter = fac.createGeometryFilter(FilterType.GEOMETRY_BBOX);
        
        String attName = ds.getSchema(TYPE_NAME).getDefaultGeometry().getName();
        filter.addLeftGeometry(fac.createAttributeExpression(attName));
        
        filter.addRightGeometry(fac.createBBoxExpression(ds.getBounds(new DefaultQuery(TYPE_NAME))));
        
        Query query=new DefaultQuery(TYPE_NAME, filter);
        
        FeatureCollection features = ds.getFeatureSource(TYPE_NAME).getFeatures(query);
        
        FeatureIterator iter = features.features();
        try{
            int count=0;
            while(iter.hasNext()){
                iter.next();
                count++;
            }
            this.totalFeatures=count;
        }finally{
            iter.close();
        }
    }

    public void testFilterNONE() throws Exception {
        FeatureSource source=ds.getFeatureSource(TYPE_NAME);

        FeatureCollection reader = source.getFeatures(Query.ALL);
        assertCorrectSize(reader);

        reader = source.getFeatures(Filter.NONE);
        assertCorrectSize(reader);

        reader = source.getFeatures(new DefaultQuery(TYPE_NAME, Filter.NONE));
        assertCorrectSize(reader);
}

    private void assertCorrectSize( FeatureCollection collection ) throws Exception{
        FeatureIterator iter = collection.features();
        
        try{
            int count=0;
            while( iter.hasNext() ){
                count++;
                iter.next();
            }
            assertEquals( this.totalFeatures, count );
            
        }finally{
            iter.close();
        }
    }

}
