package adecWatt.view.jProp;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JComponent;

@SuppressWarnings("serial")
public class JFilePreview extends JComponent {

    static public int maxInSide = 100;
    static public int border = 5;
    static public int maxOutSide = maxInSide+2*border;
    static public Dimension previewDim = new Dimension (maxOutSide, maxOutSide);

    protected ImageIcon thumbnail = null;
    protected long maxSize;

    public JFilePreview (long maxSize) {
	this.maxSize = maxSize;
	setPreferredSize (previewDim);
    }

    public void setFile (File file, boolean horizontalSpin) {
	thumbnail = getIcon (file, maxInSide, maxSize);
	if (thumbnail != null && horizontalSpin) {
	    int width = thumbnail.getIconWidth ();
	    int height = thumbnail.getIconHeight ();
	    AffineTransform at = AffineTransform.getScaleInstance (horizontalSpin ? -1 : 1, 1);
	    at.translate (horizontalSpin ? -width : 0, 0);
	    BufferedImage image = new BufferedImage (width, height, BufferedImage.TYPE_INT_ARGB);
	    image.createGraphics ().drawImage (thumbnail.getImage (), at, null);
	    thumbnail = new ImageIcon (image);
	}
	repaint ();
    }

    static public ImageIcon getIcon (File file, int thumbSide, long maxSize) {
	if (file == null || (maxSize > 0 && file.length () > maxSize))
	    return null;
	ImageIcon tmpIcon = new ImageIcon (file.getPath ());
	if (tmpIcon == null)
	    return null;
	if (tmpIcon.getIconWidth () > tmpIcon.getIconHeight ()) {
	    if (tmpIcon.getIconWidth () > thumbSide)
		tmpIcon = new ImageIcon (tmpIcon.getImage ().getScaledInstance (thumbSide, -1, Image.SCALE_DEFAULT));
	} else {
	    if (tmpIcon.getIconHeight () > thumbSide)
		tmpIcon = new ImageIcon (tmpIcon.getImage ().getScaledInstance (-1, thumbSide, Image.SCALE_DEFAULT));
	}
	return tmpIcon;
    }

    protected void paintComponent (Graphics g) {
	if (thumbnail == null)
	    return;
	int x = getWidth ()/2 - thumbnail.getIconWidth ()/2;
	int y = getHeight ()/2 - thumbnail.getIconHeight ()/2;
	// if (y < border)
	//     y = border;
	// if (x < border)
	//     x = border;

	thumbnail.paintIcon (this, g, x, y);
    }
}
