package geonoteOutils;

import javax.swing.*;
import javax.swing.border.TitledBorder;

import java.beans.*;
import java.awt.*;
import java.io.File;

public class ImagePreview extends JComponent  implements PropertyChangeListener {
	private ImageIcon thumbnail = null;
	private File file = null;
    private int largMax = 185;
    private int hautMax = 230;

    public ImagePreview(JFileChooser fc) {
        setPreferredSize(new Dimension(largMax+15, hautMax+20));
        setBorder(new TitledBorder("Aperçu")); 
        fc.addPropertyChangeListener(this);
    }

    public void loadImage() {
        if (file == null) {
            thumbnail = null;
            return;
        }

        //Don't use createImageIcon (which is a wrapper for getResource)
        //because the image we're trying to load is probably not one
        //of this program's own resources.
        ImageIcon tmpIcon = new ImageIcon(file.getPath());
        if (tmpIcon != null) {
        	int iconLarg = tmpIcon.getIconWidth();
        	int iconHaut = tmpIcon.getIconHeight();
            if ((iconLarg > largMax) || (iconHaut >hautMax)) {
            	if (iconHaut-hautMax > iconLarg-largMax) {
            		thumbnail = new ImageIcon(tmpIcon.getImage().getScaledInstance(-1, hautMax, Image.SCALE_DEFAULT));
            	} else {
            		thumbnail = new ImageIcon(tmpIcon.getImage().getScaledInstance(largMax, -1, Image.SCALE_DEFAULT));
            	}
            } else { //no need to miniaturize
                thumbnail = tmpIcon;
            }
        }
    }

    public void propertyChange(PropertyChangeEvent e) {
        boolean update = false;
        String prop = e.getPropertyName();

        //If the directory changed, don't show an image.
        if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) {
            file = null;
            update = true;

        //If a file became selected, find out which one.
        } else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {
            file = (File) e.getNewValue();
            update = true;
        }

        //Update the preview accordingly.
        if (update) {
            thumbnail = null;
            if (isShowing()) {
                loadImage();
                repaint();
            }
        }
    }

    protected void paintComponent(Graphics g) {
        if (thumbnail == null) {
            loadImage();
        }
        if (thumbnail != null) {
            int x = getWidth()/2 - thumbnail.getIconWidth()/2;
            int y = getHeight()/2 - thumbnail.getIconHeight()/2 + 6;

            if (y < 6) {
                y = 6;
            }

            if (x < 3) {
                x = 3;
            }
            thumbnail.paintIcon(this, g, x, y);
        }
    }
}
