/*
ImageBrowsePanel.java - panel to browse for and preview an image
 
 Copyright  (C) 2004-2005 Hugues Johnson
 
This program 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 2
of the License, or (at your option) any later version.
 
This program 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 this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

package com.huguesjohnson.ui;

import com.huguesjohnson.ImageLoader;
import com.huguesjohnson.fileFilter.ImageFileFilter;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;

/** ImageBrowsePanel - panel to browse for and preview an image
 * protected blocks of code were generated through the NetBeans 3.6 form editor
 * @author Hugues Johnson
 */
public class ImageBrowsePanel extends JPanel{
	/** Determines if a de-serialized file is compatible with this class. See <a href="http://java.sun.com/j2se/1.5.0/docs/guide/serialization/spec/class.html">Java Object Serialization Specifications</a>. */
	private static final long serialVersionUID=-4114219480742224281L;
	//the last path that was opened
    private static String lastPath;
    
    /** Creates a new ImageBrowsePanel.
     * @param title The title of the panel.
     */
    public ImageBrowsePanel(String title){
        //call the initComponents() method created by NetBeans
        initComponents();
        //set the title
        TitledBorder border=(TitledBorder)this.getBorder();
        border.setTitle(title);
        //get the last opened path
        String lastPath=System.getProperty("last-open-path");
        if(lastPath==null){
            lastPath=System.getProperty("user.dir");
        }
        ImageBrowsePanel.lastPath=lastPath;
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents() {//GEN-BEGIN:initComponents
    	this.labelImagePreview = new javax.swing.JLabel();
    	this.labelImagePath = new javax.swing.JLabel();
    	this.textFieldImagePath = new javax.swing.JTextField();
    	this.buttonBrowse = new javax.swing.JButton();

    	this.setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.X_AXIS));

    	this.setBorder(new javax.swing.border.TitledBorder(""));
    	this.labelImagePreview.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    	this.labelImagePreview.setText("Preview");
    	this.labelImagePreview.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED));
    	this.labelImagePreview.setMaximumSize(new java.awt.Dimension(128, 128));
    	this.labelImagePreview.setMinimumSize(new java.awt.Dimension(64, 64));
    	this.labelImagePreview.setPreferredSize(new java.awt.Dimension(64, 64));
    	this.labelImagePreview.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    	this.labelImagePreview.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    	this.add(this.labelImagePreview);

    	this.labelImagePath.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
    	this.labelImagePath.setText("Path: ");
    	this.labelImagePath.setToolTipText("Path to the thumbnail image");
    	this.labelImagePath.setMaximumSize(new java.awt.Dimension(40, 15));
    	this.labelImagePath.setMinimumSize(new java.awt.Dimension(40, 15));
    	this.labelImagePath.setPreferredSize(new java.awt.Dimension(40, 15));
    	this.add(this.labelImagePath);

    	this.textFieldImagePath.setEditable(false);
    	this.textFieldImagePath.setToolTipText("Path to the thumbnail image");
    	this.textFieldImagePath.setMaximumSize(new java.awt.Dimension(2147483647, 21));
    	this.textFieldImagePath.setMinimumSize(new java.awt.Dimension(200, 21));
    	this.textFieldImagePath.setPreferredSize(new java.awt.Dimension(200, 21));
    	this.add(this.textFieldImagePath);

    	this.buttonBrowse.setText("Browse");
    	this.buttonBrowse.setToolTipText("Browse for a thumbnail image");
    	this.buttonBrowse.setActionCommand("BrowseThumbnail");
    	this.buttonBrowse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonBrowseActionPerformed(evt);
            }
        });

    	this.add(this.buttonBrowse);

    }//GEN-END:initComponents

    void buttonBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonBrowseActionPerformed
        if(this.browse()){
            this.onBrowseComplete();
        }
    }//GEN-LAST:event_buttonBrowseActionPerformed
    
    /** Opens a JFileChoose to browse for an image.
     * @return True if a new image was selected.
     */
    public boolean browse(){
        boolean success=true;
        JFileChooser fileChooser=new JFileChooser();
        //do not allow multiple selections
        fileChooser.setMultiSelectionEnabled(false);
        //only accept specific file filters
        fileChooser.setAcceptAllFileFilterUsed(false);
        //set the current directory
        String filePath=this.getImagePath();
        if(filePath.length()>0){
            fileChooser.setCurrentDirectory(new File(filePath));
        } else{
            fileChooser.setCurrentDirectory(new File(ImageBrowsePanel.lastPath));
        }
        //set the file filter
        fileChooser.setFileFilter(new ImageFileFilter());
        //show the file chooser
        int returnValue=fileChooser.showOpenDialog(this);
        //was 'OK' selected?
        if(returnValue==JFileChooser.APPROVE_OPTION){
            //set the image
            this.setImage(fileChooser.getSelectedFile().getPath());
            //save the path
            String currentDirectoryPath=fileChooser.getCurrentDirectory().getPath();
            ImageBrowsePanel.lastPath=currentDirectoryPath;
            System.setProperty("last-open-path",currentDirectoryPath);
        } else{
            success=false;
        }
        return(success);
    }

    /** Event that fires after a browse has completed successfully.
     */
    public void onBrowseComplete(){ }    
    
    /** Sets the image for the dialog, updates the textfield and image.
     * @param imagePath The full path to the new image file.
     */
    public void setImage(String imagePath){
        //display the image
        BufferedImage image=ImageLoader.loadBufferedImage(imagePath);
        if(image!=null){
            //set the textfield
            this.textFieldImagePath.setText(imagePath);
            //draw the image
            this.labelImagePreview.setIcon(new ImageIcon(image));
        }
    }

    /** Returns the full path to the image file.
     * @return The full path to the image file.
     */
    public String getImagePath(){
        return(this.textFieldImagePath.getText());
    }

    /** Returns a BufferedImage loaded from the image file.
     * @return A BufferedImage or null if an error occurs or no file is selected.
     */
    public BufferedImage getImage(){
        return(ImageLoader.loadBufferedImage(this.getImagePath()));
    }
    
    /** Returns the full directory of the current path.
     * @return The full directory name of the current path.
     */
    public String getDirectory(){
        String path=(this.getImagePath());
        if(!path.endsWith(File.separator)){
            int lastIndexOf=path.lastIndexOf(File.separator);
            if((lastIndexOf>0)&&(lastIndexOf<path.length())){
                path=path.substring(0,lastIndexOf+1);
            }
        }
        return(path);
    }
    
    /** Clears the textfield and image.
     */
    public void clear(){
        this.textFieldImagePath.setText("");
        this.labelImagePreview.setIcon(null);
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonBrowse;
    private javax.swing.JLabel labelImagePath;
    private javax.swing.JLabel labelImagePreview;
    private javax.swing.JTextField textFieldImagePath;
    // End of variables declaration//GEN-END:variables
}