/*
 * Copyright (c) 2005-2010 KOM – Multimedia Communications Lab
 *
 * This file is part of PeerfactSim.KOM.
 * 
 * PeerfactSim.KOM is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 * 
 * PeerfactSim.KOM is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with PeerfactSim.KOM.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package de.tud.kom.p2psim.impl.topology.movement.modularosm.mapvisualization;

import java.awt.AlphaComposite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import javax.swing.JComponent;
import javax.swing.JMenu;

import de.tud.kom.p2psim.api.topology.Topology;
import de.tud.kom.p2psim.impl.topology.PositionVector;
import de.tud.kom.p2psim.impl.topology.movement.modularosm.GPSCalculation;
import de.tud.kom.p2psim.impl.topology.views.VisualizationTopologyView.VisualizationInjector;
import de.tudarmstadt.maki.simonstrator.api.Binder;
import de.tudarmstadt.maki.simonstrator.api.component.ComponentNotAvailableException;

public class ShowMapQuestMapViz extends JComponent
		implements IMapVisualization {

	private String tempImageFilePath;

	private String mapType;

	private String mapQuestKey;
	
	private BufferedImage background = null;

	private BufferedImage storedImage;

	private boolean initialized = false;


	public ShowMapQuestMapViz() {
		setBounds(0, 0, VisualizationInjector.getWorldX(),
				VisualizationInjector.getWorldY());
		setOpaque(true);
		setVisible(true);
	}

	private void initializeImage() {
		if (!initialized) {
			PositionVector worldDimensions = Binder.getComponentOrNull(Topology.class)
					.getWorldDimensions();

			tempImageFilePath = tempImageFilePath + "mapquest"
					+ GPSCalculation.getLatCenter() + "_"
					+ GPSCalculation.getLonCenter() + "_" + GPSCalculation.getZoom() + "_"
					+ worldDimensions.getX() + "_"
					+ worldDimensions.getY() + mapType + ".jpg";

			// Check if the file with same properties (same location) already
			// exists
			File f = new File(tempImageFilePath);
			if (!f.exists()) {
				try {
					//Based on the meters per pixel, the needed height and width in pixels can be determined.
					int pxx = (int) (worldDimensions.getX() / GPSCalculation.getMetersPerPixel());
					int pxy = (int) (worldDimensions.getY() / GPSCalculation.getMetersPerPixel());

					String imageUrl = "http://www.mapquestapi.com/staticmap/v4/getmap?key="
							+ mapQuestKey + "&type=" + mapType
							+ "&imagetype=jpeg&center="
							+ GPSCalculation.getLatCenter() + ","
							+ GPSCalculation.getLonCenter() + "&zoom="
							+ ((GPSCalculation.getZoom())) + "&size="
							+ pxx + ","
							+ pxy;

					URL url = new URL(imageUrl);
					InputStream is = url.openStream();
					OutputStream os = new FileOutputStream(tempImageFilePath);

					byte[] b = new byte[2048];
					int length;

					while ((length = is.read(b)) != -1) {
						os.write(b, 0, length);
					}

					is.close();
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			initialized = true;
			
			// Create a media tracker and add the image to it.  If we had several 
	        // images to load, they could all be added to the same media tracker. 
	        MediaTracker tracker = new MediaTracker(this); 
	        Image image = Toolkit.getDefaultToolkit().getImage(tempImageFilePath);
	        tracker.addImage(image, 0);

	        // Start downloading the image and wait until it finishes loading. 
	        try { 
	            tracker.waitForAll(); 
	        } catch(InterruptedException e) {
	        	// help?
	        }
	        background = resize(
					Toolkit.getDefaultToolkit().getImage(tempImageFilePath),
					VisualizationInjector.getWorldX(),
					VisualizationInjector.getWorldY());
	        
		}
	}

	@Override
	public void paint(Graphics g) {
		initializeImage();

		super.paintComponent(g);
		Graphics2D g2 = (Graphics2D) g;
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
				RenderingHints.VALUE_ANTIALIAS_ON);
		g2.setComposite(
				AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f));
		if (background != null) {
			g2.drawImage(background, 0, 0, this);
		}
	}

	public void setTempImageFilePath(String tempImageFilePath) {
		this.tempImageFilePath = tempImageFilePath;
	}

	public void setMapType(String mapType) {
		this.mapType = mapType;
	}

	public void setMapQuestKey(String mapQuestKey) {
		this.mapQuestKey = mapQuestKey;
	}

	/**
	 * Resizes the given image to the given width and height
	 *
	 * @param originalImage
	 * @param width
	 * @param height
	 */
	private BufferedImage resize(Image originalImage, int width, int height) {
		int type = BufferedImage.TYPE_INT_ARGB;
		BufferedImage resizedImage = new BufferedImage(width, height, type);
		Graphics2D g = resizedImage.createGraphics();

		g.setComposite(AlphaComposite.Src);
		g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
				RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		g.setRenderingHint(RenderingHints.KEY_RENDERING,
				RenderingHints.VALUE_RENDER_QUALITY);
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
				RenderingHints.VALUE_ANTIALIAS_ON);

		g.drawImage(originalImage, 0, 0, width, height, this);

		g.dispose();

		storedImage = resizedImage;
		return resizedImage;
	}

	@Override
	public BufferedImage getMapImage()
	{
		if(storedImage == null)
		{
			initializeImage();
			resize(Toolkit.getDefaultToolkit().getImage(tempImageFilePath),
					VisualizationInjector.getWorldX(),
					VisualizationInjector.getWorldY());
		}
		return storedImage;
	}

	@Override
	public String getDisplayName() {
		return "MapQuest Map";
	}

	@Override
	public JComponent getComponent() {
		return this;
	}

	@Override
	public JMenu getCustomMenu() {
		return null;
	}

	@Override
	public boolean isHidden() {
		return false;
	}
}
