package collembola;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Random;

import javax.swing.JFrame;

import mcmas.core.MCMChrono;

import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
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.GeometryFactory;
import com.vividsolutions.jts.geom.MultiPolygon;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Point;

public class MapMain {
	
	/*
	public void displayLayers(File shpFile) throws IOException {
		System.out.println(shpFile);
		
		FileDataStore store = FileDataStoreFinder.getDataStore(shpFile);
		
		System.out.println(shpFile.length());
		SimpleFeatureSource shapefileSource = store.getFeatureSource();
		
		Style style = SLD.createPolygonStyle(Color.GREEN, null, 0.0f);
		
		final MapContent map = new MapContent();
		map.setTitle("Test display GIS");
		
		Layer shpLayer = new FeatureLayer(shapefileSource, style);
		map.addLayer(shpLayer);
		
		JMapFrame frame = new JMapFrame(map);
		frame.setSize(800, 600);
		frame.enableStatusBar(true);
		frame.enableToolBar(true);
		frame.setVisible(true);
	}*/
	
	public void displayLayers2(URL shpFile) throws IOException {
		ShapefileDataStore store = new ShapefileDataStore(shpFile);
		String name = store.getTypeNames()[0];
		SimpleFeatureSource source = store.getFeatureSource(name);
		SimpleFeatureCollection collection = source.getFeatures();
		SimpleFeatureIterator it = collection.features();
		GeometryFactory gf = new GeometryFactory();
		
		ReferencedEnvelope env = source.getBounds();
		
		int pict_width = (int) Math.ceil(env.getMaxX() - env.getMinX());
		int pict_height = (int) Math.ceil(env.getMaxY() - env.getMinY());
		
		System.out.println(pict_width);
		System.out.println(pict_height);
		
		//Point [][] points = new Point[256][256];
		String [][] grid = new String[256][256];
		
		HashMap<String, Integer> colorMap = new HashMap<String, Integer>();
		Random rng = new Random();
		
		//int index = 0;
		
		MCMChrono ch = new MCMChrono("interections").start();
		
		/*
		for (int i = 0; i < points.length; i++) {
			for (int j = 0; j < points[i].length; j++) {
				final double xpos = transform(i + 0.5, 0, grid.length, env.getMinX(), env.getMaxX());
				final double ypos = transform(j + 0.5, 0, grid[i].length, env.getMinY(), env.getMaxY());
				points[i][j] = gf.createPoint(new Coordinate(xpos, ypos));
			}
		}*/
		
		while (it.hasNext()) {
			//index++;
			SimpleFeature f = it.next();
			//Polygon p = new Polygon();
			
			//System.out.println(f.getProperty("level1"));
			//System.out.println(f.getProperties());
			MultiPolygon poly = (MultiPolygon) f.getDefaultGeometry();
			//Coordinate[] c = poly.getCoordinates();
			colorMap.put(f.getID(), rng.nextInt());
			
			System.out.println(f.getID());
			System.out.println(f.getAttribute("Level1"));
			
			//System.out.println(poly.getCentroid());
			//System.out.println(c.length);
			
			for (int i = 0; i < grid.length; i++) {
				for (int j = 0; j < grid[i].length; j++) {
					if (grid[i][j] != null) continue;
					
					final double xpos = transform(i + 0.5, 0, grid.length, env.getMinX(), env.getMaxX());
					final double ypos = transform(j + 0.5, 0, grid[i].length, env.getMinY(), env.getMaxY());
					
					//if (grid[i][j] != null) continue;
					
					//System.out.println("xpos: " + xpos);
					//System.out.println("ypos: " + ypos);
					Point point = gf.createPoint(new Coordinate(xpos, ypos));
					//final Point point = points[i][j];
					
					if (poly.contains(point)) {
						/*System.out.println("xpos: " + xpos);
						System.out.println("ypos: " + ypos);
						System.out.println("true");*/
						grid[i][j] = f.getID();
					}
				}
			}
		}
		
		System.out.println(ch.stop());
		
		ch = new MCMChrono("image generation").start();
		
		BufferedImage img = new BufferedImage(grid.length, grid.length, ColorSpace.TYPE_RGB);
		
		for (int i = 0; i < grid.length; i++) {
			for (int j = 0; j < grid[i].length; j++) {
				/*if (! colorMap.containsKey(grid[i][j])) {
					colorMap.put(grid[i][j], rng.nextInt());
				}*/
				
				//System.out.print("" + j + " ");
				//System.out.println(grid.length - j);
				Integer c = colorMap.get(grid[i][j]);
				
				if (c != null)
					img.setRGB(i, grid.length - 1 - j, c);
				//System.out.print(grid[i][j] + " ");
			}
			//System.out.println();
		}
		
		System.out.println(ch.stop());
		
		//ImageIO.write(img, "png", new File("out.png"));
		
		System.out.println(source.getBounds());
		//BufferedImage img = new BufferedImage(20000, height, imageType)
		
		System.out.println(transform(128, 0, 256, 0, 1000));
		
		System.out.println(img);
		ImagePanel panel = new ImagePanel(img);
		JFrame frame = new JFrame("MapGIS");
		frame.setContentPane(panel);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
		
	}
	
	public double transform(double n, double min1, double max1, double min2, double max2) {
		final double range1 = max1 - min1;
		final double range2 = max2 - min2;
		
		//System.out.println(range1);
		//System.out.println(range2);
		return ((n - min1) / range1) * range2 + min2;
	}
	
	public static void test(String[] args) throws IOException {
		File file = new File("110m_cultural\\110m_admin_0_countries.shp");
        FileDataStore store = FileDataStoreFinder.getDataStore(file);
        SimpleFeatureSource featureSource = store.getFeatureSource();
        SimpleFeatureCollection c = featureSource.getFeatures();
        SimpleFeatureIterator featuresIterator = c.features();
       
        while (featuresIterator.hasNext()) {
            SimpleFeature o = featuresIterator.next();
            
            String name = (String) o.getAttribute("NAME");
            Object geometry = o.getDefaultGeometry();
            System.out.println(name + ", " + geometry.getClass());
        }
	}
	
	public static void main(String[] args) throws IOException {
		//ClassLoader cl = ClassLoader.getSystemClassLoader();
		 
        //URL[] urls = ((URLClassLoader)cl).getURLs();
 
        /*for(URL url: urls){
        	System.out.println(url.getFile());
        }*/
        
		//new MapMain().displayLayers(new File("site4.shp"));
        new MapMain().displayLayers2(new URL("file://data/site4.shp"));
	}
}
