package test;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

import org.geotools.feature.Feature;
import org.geotools.feature.FeatureCollection;
import org.geotools.map.DefaultMapContext;

import org.geotools.map.MapContext;
import org.geotools.renderer.lite.LiteRenderer;
import org.geotools.styling.LineSymbolizer;
import org.geotools.styling.Style;
import org.geotools.styling.StyleBuilder;

import com.vividsolutions.jts.geom.Envelope;

import com.un7emesens.configuration.Configuration;
import com.un7emesens.utils.UtilsForLocalisation;
import com.un7emesens.utils.UtilsForPostGIS;

public class WorldImageViaWms {
	
	private static int LARGEUR_IMAGE = 500;
	
	private static int LARGEUR_ECRAN = 600;

	private static int HAUTEUR_IMAGE = 500;

	private static int HAUTEUR_ECRAN = 600;
	
	private static String[] LISTE_COVERAGES_20K = {
		"fra20k_028_040_l_l_nt_v21_Coverage",
		"fra20k_028_041_l_l_nt_v21_Coverage",
		"fra20k_028_042_l_l_nt_v21_Coverage"
	};
	
	private static boolean DEBUG = true;
	
	// ****
	// Main
	// ****
	
	public static void main(String[] args) {
		testWorldImageViaWms();
	}
	
	
	public static void testWorldImageViaWms() {
		
		try {
			MapContext mapContext = new DefaultMapContext();
			StyleBuilder styleBuilder = new StyleBuilder();
			Envelope envelope = new Envelope();
					
			// On charge le département (pour obtenir l'enveloppe)
			
			FeatureCollection fcDepartement = UtilsForLocalisation.getDepartement(UtilsForPostGIS.pgDatastore(), "92");
			Feature fDepartement = fcDepartement.features().next();
			
			LineSymbolizer lS1 = styleBuilder.createLineSymbolizer(Color.YELLOW, 1);
			LineSymbolizer lS2 = styleBuilder.createLineSymbolizer(Color.RED, 5);
			Style styleDepartement = styleBuilder.createStyle();
			styleDepartement.addFeatureTypeStyle(styleBuilder.createFeatureTypeStyle(null, styleBuilder.createRule(lS2)));
			styleDepartement.addFeatureTypeStyle(styleBuilder.createFeatureTypeStyle(null, styleBuilder.createRule(lS1)));
			envelope = fDepartement.getBounds();
			
			mapContext.addLayer(fcDepartement, styleDepartement);			
			
			debug("xMax département >" + envelope.getMaxX());
			debug("yMax département >" + envelope.getMaxY());
			debug("xMin département >" + envelope.getMinX());
			debug("yMin département >" + envelope.getMinY());
			
			
			// On charge le raster associé
			
			String urlString = "http://127.0.0.1:8080/geoserver/wms?"
				+ "bbox=" + envelope.getMinX() + "," + envelope.getMinY() + "," + envelope.getMaxX() + "," + envelope.getMaxY()
				+ "&format=image/png&request=GetMap&srs=EPSG:4326&width=" + LARGEUR_ECRAN + "&height=" + HAUTEUR_ECRAN;
			
			String strStyles = "";
			String strLayers = "";
			
			for (int i = 0 ; i < LISTE_COVERAGES_20K.length ; i++) {
				strStyles = addToString("raster", strStyles);
				strLayers = addToString(LISTE_COVERAGES_20K[i], strLayers);
			}
			
			urlString = urlString + "&styles=" + strStyles + "&layers=" + strLayers;
			
			BufferedImage rasters = null;
			
			try {
				URL url = new URL(urlString);
				debug("WMS URL: " + urlString);
				rasters = ImageIO.read(url);
			} catch (java.io.IOException ioe) {
				debug("WMS Unavailable");
			}
			
			if (rasters == null) {
				debug("WMS Returned Nothing");
			}
			
			debug("WMSData ::: bimage dimensions ::: " + rasters.getWidth() + " , " + rasters.getHeight()); 
			
			// Traitement de l'affichage
			
			debug("xMax >" + envelope.getMaxX());
			debug("yMax >" + envelope.getMaxY());
			debug("xMin >" + envelope.getMinX());
			debug("yMin >" + envelope.getMinY());
			
			BufferedImage image = new BufferedImage((int) LARGEUR_IMAGE, (int) HAUTEUR_IMAGE, BufferedImage.TYPE_INT_ARGB );
			LiteRenderer rend = new LiteRenderer(mapContext);
			Graphics2D g2d = (Graphics2D) image.getGraphics();
			rend.paint(g2d, new Rectangle((int) LARGEUR_IMAGE, (int) HAUTEUR_IMAGE), envelope);			
			
			JLabel label = new JLabel();
			label.setIcon(createImageIcon(rasters, image, LARGEUR_ECRAN, HAUTEUR_ECRAN));
			label.setSize((int) LARGEUR_IMAGE, (int) HAUTEUR_IMAGE);
			label.setPreferredSize(new Dimension((int) LARGEUR_IMAGE, (int) HAUTEUR_IMAGE));
			JFrame frame = new JFrame();
			frame.add(label, BorderLayout.CENTER);
			frame.setTitle("Essai WorldImage via WMS");
			frame.setSize((int) LARGEUR_ECRAN, (int) HAUTEUR_ECRAN);
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame.setVisible(true);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public static ImageIcon createImageIcon(BufferedImage image1, BufferedImage image2,
			int iLargeur, int iHauteur){
		
		BufferedImage mergedImage = new BufferedImage(iLargeur, iHauteur, BufferedImage.TYPE_INT_RGB);
		Graphics2D mergeGc = mergedImage.createGraphics();
		
		mergeGc.drawImage(image1,0,0,iLargeur,iHauteur, null);
		mergeGc.drawImage(image2,0,0,iLargeur,iHauteur, null);
		
		return new ImageIcon(mergedImage);
	} 
	
	public static String addToString(String strStringToAdd, String strOldString) {
		if (strOldString.contentEquals("")) {
			return strStringToAdd;
		}
		
		return strOldString + "," + strStringToAdd;
 	}

	private static void debug(String strIn) {
		
		if (Configuration.getOkDebug() && DEBUG) {
			System.out.println("[DEBUG_GeotiffTest] " + strIn);
		}
	}
}
