package SE4.abstraction;

//Sur une idee de Cedric Dumas
import java.awt.*;
import java.awt.image.*;
import java.io.File;
import javax.swing.ImageIcon;

public class Photo extends ImageIcon {
	private static final long serialVersionUID = 1L;
	// Constantes
	private final float ZOOM_MIN = 0.1f;
	private final float ZOOM_MAX = 5.0f;
	private final float ICON_SIZE = 40.0f;
	
	// Variables d'instance
	private int largeurInit;
	private int hauteurInit;
	private Image image;
	private float zoom;
	private String nom;

	/**
	 * Constructeur initialisant l'album avec toutes les photos situees dans le repertoire filename
	 * @param filename chemin complet du fichier image
	 */
	public Photo(String filename) {
		super(filename);
		this.largeurInit = this.getIconWidth();
		this.hauteurInit = this.getIconHeight();
		this.image = this.getImage();
		this.zoom = 1.0f;
		this.nom = (new File(filename)).getName();
		this.nom = this.nom.substring(0, this.nom.length() - 4);
	}

	/**
	 * Retourne les dimensions de la photo
	 * @return les dimensions de la photo.
	 */
	public Dimension getSize() {
		return new Dimension(this.getIconWidth(), this.getIconHeight());
	}

	/**
	 * Retourne le facteur de zoom
	 * @return le facteur de zoom
	 */
	public int getZoom() {
		return ((int) (this.zoom * 100));
	}

	/**
	 * Retourne le nom de la photo
	 *  @return le nom de la photo
	 */
	public String getNom() {
		return this.nom;
	}

	/**
	 * Retourne une icone de la photo de dimension maximale ICON_SIZE
	 *  @return une icone de la photo de dimension maximale ICON_SIZE
	 */
	public ImageIcon getIcone() {
		float ratio = Math.max(this.largeurInit, this.hauteurInit);
		int largeur = (int) (ICON_SIZE * (float) this.largeurInit / ratio);
		int hauteur = (int) (ICON_SIZE * (float) this.hauteurInit / ratio);

		BufferedImage buf = new BufferedImage(largeur, hauteur,	BufferedImage.TYPE_INT_ARGB);

		Graphics2D g = buf.createGraphics();
		g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		g.drawImage(this.image, 0, 0, largeur, hauteur, null);
		g.dispose();

		return (new ImageIcon(buf));
	}

	/**
	 * Redimensionne la photo en lui appliquant le facteur de zoom passe en parametre.
	 * @param zoom facteur de zoom du redimensionnement.
	 */
	public void redimensionner(float zoom) 	{
		this.zoom = Math.min(Math.max(zoom/100 , ZOOM_MIN), ZOOM_MAX);

		int largeur = (int) (largeurInit * this.zoom);
		int hauteur = (int) (hauteurInit * this.zoom);
		BufferedImage buf = new BufferedImage(largeur, hauteur, BufferedImage.TYPE_INT_ARGB);

		Graphics2D g = buf.createGraphics();
		g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		g.drawImage(this.image, 0, 0, largeur, hauteur, null);
		g.dispose();

		this.setImage(buf);
	}
}