package collembola.model;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.geotools.data.shapefile.ng.ShapefileDataStore;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.opengis.feature.simple.SimpleFeature;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.MultiPolygon;
import com.vividsolutions.jts.geom.Point;

public class CollemLoader {
	
	public static CollemModel load(int x, int y, URL shpFile) {
		SimpleFeatureSource source;
		SimpleFeatureCollection collection;
		ReferencedEnvelope env;
		
		try {
			ShapefileDataStore store = new ShapefileDataStore(shpFile);
			store.setMemoryMapped(true);
			
			String name = store.getTypeNames()[0];
			source = store.getFeatureSource(name);
			collection = source.getFeatures();
			env = source.getBounds();
		} catch (IOException e) {
			throw new RuntimeException("Error parsing shapefile", e);
		};

		int index = 0;
		System.out.println(collection.size());
		SimpleFeatureIterator it = collection.features();
		GeometryFactory gf = new GeometryFactory();
		//CollemCell[][] grid = model.getGrid();
		
		CollemModel model = new CollemModel(x, y, collection.size());
		int [] plotSurfaces = model.getPlotsSurfaces();
		
		try {
			while (it.hasNext()) {
				SimpleFeature f = it.next();
				MultiPolygon poly = (MultiPolygon) f.getDefaultGeometry();
				
				//System.out.println("Rasterizing shape #" + index);
				
				for (int i = 0; i < x; i++) {
					for (int j = 0; j < y; j++) {
						//final CollemCell cell = grid[i][j];
								
						if (model.getPatchOwner(i, j) != -1) continue;
						
						final double xpos = transform(i + 0.5, 0, x, env.getMinX(), env.getMaxX());
						final double ypos = transform(j + 0.5, 0, y, env.getMinY(), env.getMaxY());
						
						Point point = gf.createPoint(new Coordinate(xpos, ypos));
						
						if (poly.contains(point)) {
							model.setPatchOwner(i, j, index);
							model.setPatchType(i, j, (Integer) (f.getAttribute("Level1")));
							plotSurfaces[index]++;
							//System.out.println("Set " + i + ", " + j + " to " + cell);
						}
					}
				}
				
				index++;
			}
		} finally {
			//it.close();
		}
		
		//System.out.println(model);
		return model;
	}
	
	public static double transform(double n, double min1, double max1, double min2, double max2) {
		final double range1 = max1 - min1;
		final double range2 = max2 - min2;
		return ((n - min1) / range1) * range2 + min2;
	}
	
	public static void main(String[] args) throws MalformedURLException {
		/*CollemModel model =*/ CollemLoader.load(256, 256, new URL("file://data/site4.shp"));
		//model.savePicture();
	}

}
