/*
ImageBrowsePanel.java - panel to browse for a file
 
 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 java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileFilter;

/** FileBrowsePanel - panel to browse for a file
 * protected blocks of code were generated through the NetBeans 3.6 form editor
 * @author Hugues Johnson
 */
public class FileBrowsePanel 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=-4285415441734931402L;
	//the last path opened
    private static String lastPath;
    //filters to use when browsing
    private FileFilter[] filters;
    /** Default value for showing the browse button. */
    public final static boolean DEFAULT_SHOW_BROWSE_BUTTON=true;

    /** Creates a new FileBrowsePanel.
     * @param title The title of the panel.
     * @param filters A list of file filters to accept.
     */
    public FileBrowsePanel(String title,FileFilter[] filters){
        this.init(title,filters,DEFAULT_SHOW_BROWSE_BUTTON);
    }    

    /** Creates a new FileBrowsePanel with a single file filter.
     * @param title The title of the panel.
     * @param filter The file filter to accept.
     */
    public FileBrowsePanel(String title,FileFilter filter){
        FileFilter[] filters=new FileFilter[1];
        filters[0]=filter;
        this.init(title,filters,DEFAULT_SHOW_BROWSE_BUTTON);
    }    
    
    /** Creates a new FileBrowsePanel.
     * @param title The title of the panel.
     * @param filters A list of file filters to accept.
     * @param showBrowseButton Whether or not to show the browse button.
     */
    public FileBrowsePanel(String title,FileFilter[] filters,boolean showBrowseButton){
        this.init(title,filters,showBrowseButton);
    }

    /** Creates a new FileBrowsePanel with a single file filter.
     * @param title The title of the panel.
     * @param filter The file filter to accept.
     * @param showBrowseButton Whether or not to show the browse button.
     */
    public FileBrowsePanel(String title,FileFilter filter,boolean showBrowseButton){
        FileFilter[] filters=new FileFilter[1];
        filters[0]=filter;
        this.init(title,filters,showBrowseButton);
    }    
    
    /** Creates a new FileBrowsePanel, accepts (*.*). 
     * @param title The title of the panel.
     */
    public FileBrowsePanel(String title){
        this.init(title,(new FileFilter[0]),DEFAULT_SHOW_BROWSE_BUTTON);
    }    

    /** Creates a new FileBrowsePanel, accepts (*.*). 
     * @param title The title of the panel.
     * @param showBrowseButton Whether or not to show the browse button.
     */
    public FileBrowsePanel(String title,boolean showBrowseButton){
        this.init(title,(new FileFilter[0]),showBrowseButton);
    }    
    
    /** Initializes the form. 
     * @param title the title of the panel
     * @param filters a list of file filters to accept
     * @param showBrowseButton whether or not to show the browse button
     */
    private void init(String title,FileFilter[] filters,boolean showBrowseButton){
        //call the initComponents method generated by NetBeans
        initComponents();
        //set the title
        TitledBorder border=(TitledBorder)this.getBorder();
        border.setTitle(title);
        //set file filters
        this.filters=filters;
        //look for the last path
        String lastPath=System.getProperty("last-open-path");
        if(lastPath==null){
            lastPath=System.getProperty("user.dir");
        }
        FileBrowsePanel.lastPath=lastPath;
        //hide the browse button
        if(!showBrowseButton){
            this.buttonBrowse.setVisible(false);
        }
    }    
    
    /** 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.labelPath = new javax.swing.JLabel();
        this.textFieldPath = 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.labelPath.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        this.labelPath.setText("Path: ");
        this.labelPath.setToolTipText("Path to the thumbnail image");
        this.labelPath.setMaximumSize(new java.awt.Dimension(40, 15));
        this.labelPath.setMinimumSize(new java.awt.Dimension(40, 15));
        this.labelPath.setPreferredSize(new java.awt.Dimension(40, 15));
        this.add(this.labelPath);

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

        this.buttonBrowse.setText("Browse");
        this.buttonBrowse.setToolTipText("Browse for a file");
        this.buttonBrowse.setActionCommand("BrowseThumbnail");
        this.buttonBrowse.setMaximumSize(null);
        this.buttonBrowse.setMinimumSize(null);
        this.buttonBrowse.setPreferredSize(null);
        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

    public void buttonBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonBrowseActionPerformed
        if(this.browse()){
            this.onBrowseComplete();
        }
    }//GEN-LAST:event_buttonBrowseActionPerformed

    /** Opens a JFileChooser with the supported filters.
     * @return True if the file changed.
     */
    public boolean browse(){
        boolean success=true;
        JFileChooser fileChooser=new JFileChooser();
        //do not allow multiple selections
        fileChooser.setMultiSelectionEnabled(false);
        //add filters
        int filterCount=this.filters.length;
        if(filterCount<1){
            //no filters specified, accept everything
            fileChooser.setAcceptAllFileFilterUsed(true);
        } else{
            fileChooser.setAcceptAllFileFilterUsed(false);
            for(int index=0;index<filterCount;index++){
                fileChooser.setFileFilter(this.filters[index]);
            }
        }
        //set the current directory
        String filePath=this.getFilePath();
        if(filePath.length()>0){
            fileChooser.setCurrentDirectory(new File(filePath));
        } else{
            fileChooser.setCurrentDirectory(new File(FileBrowsePanel.lastPath));
        }
        //show the file chooser
        int returnValue=fileChooser.showOpenDialog(this);
        //was 'OK' selected?
        if(returnValue==JFileChooser.APPROVE_OPTION){
            this.setFilePath(fileChooser.getSelectedFile().getPath());
            //save the last path
            String currentDirectoryPath=fileChooser.getCurrentDirectory().getPath();
            FileBrowsePanel.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 file path textfield.
     * @param filePath The new path.
     */
    public void setFilePath(String filePath){
        this.textFieldPath.setText(filePath);
    }
    
    /** Returns the file path in the textfield.
     * @return File path in the textfield.
     */
    public String getFilePath(){
        return(this.textFieldPath.getText());
    }
    
    /** Returns the full directory of the current path.
     * @return full directory name of the current path.
     */
    public String getDirectory(){
        String path=(this.getFilePath());
        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.
     */
    public void clear(){
        this.textFieldPath.setText("");
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonBrowse;
    private javax.swing.JLabel labelPath;
    private javax.swing.JTextField textFieldPath;
    // End of variables declaration//GEN-END:variables
}