/*******************************************************************************
 * This file is part of GECAMed.
 * 
 * GECAMed is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License (L-GPL) as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GECAMed 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 Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License (L-GPL)
 * along with GECAMed.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * GECAMed is Copyrighted by the Centre de Recherche Public Henri Tudor (http://www.tudor.lu)
 * (c) CRP Henri Tudor, Luxembourg, 2008
 *******************************************************************************/
/*
 * FileSelectorPanel.java
 *
 * Created on February 24, 2004, 11:06 AM
 */

package lu.tudor.santec.gecamed.core.gui.widgets;

																			 
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.filechooser.FileFilter;

import lu.tudor.santec.i18n.Relocalizable;
import lu.tudor.santec.i18n.SwingLocalizer;
import lu.tudor.santec.i18n.Translatrix;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

//***************************************************************************
//* Class Defintition                                                       *
//***************************************************************************

//***************************************************************************
/** The FileSelectorPanel class implements a JPanel, allowing either to manually
 * specify a file or alternatively via a JFileChooser. The FileSelectorPanel appears
 * as a JTextField to specify the file manually as well as a "Browse" button.
 * Whenever file selction changes, the panel fires a PropertyChangeEvent. The
 * public constant c_FileSelectionChanged defines the name of the property
 * @author lu.tudor.santec/Nico MACK
 */
//***************************************************************************

public class FileSelectorPanel extends JPanel implements ActionListener,
                                                         Relocalizable
    {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Component               m_Owner;
 	
    private String					m_FileLabelKey;
    private JLabel                  m_FileLabel;
    private JTextField              m_FileName;
    private String                  m_FilePath;
    private JButton                 m_BrowseButton;
    private int                     m_Mode;

    private File                    m_ChosenFile;
    private FileFilter              m_FileFilter;
    
    private static File             m_LastDirectory;
    
//***************************************************************************
//* Class Constants                                                         *
//***************************************************************************

    public static final String c_FileSelectionChanged = "FileSelectionChanged";
    
    public static final int    c_ForLoading    =   1;
    public static final int    c_ForSaving     =   2;
    public static final int    c_ChooseFolder  =   3;

	private final static String c_Columns		= "3dlu,fill:max(75dlu;pref):grow," +
	  											  "3dlu,fill:max(25dlu;pref),3dlu";

	private final static String c_Rows			= "3dlu,fill:pref," +
	  											  "3dlu,fill:pref,3dlu";

//***************************************************************************
//* Constructor(s)                                                          *
//***************************************************************************

//---------------------------------------------------------------------------
/** Creates a new instance of FileSelectorPanel.
 * @param p_Parent The parent window this FileSelectorPanel is to become a child of.
 * @param p_TextLabel Label to be displayed above the TextField used for specifying the file manually
 * @param p_Mode specifies the mode to use the newly created FileSelectorPanel in. Possible
 * values are c_ForLoading, c_ForSaving abd c_ChooseFolder.
 *
 */    
//---------------------------------------------------------------------------

public FileSelectorPanel (Component p_Owner, String p_FileLabelKey, int p_Mode)
    {
    m_Owner = p_Owner;
	CellConstraints	l_Constraints;
	FormLayout		l_Layout;	
       
	l_Constraints = new CellConstraints ();	
	l_Layout = new FormLayout(c_Columns, c_Rows);
	this.setLayout (l_Layout);
	
	m_FileLabelKey = p_FileLabelKey;
    m_FileLabel = new JLabel (Translatrix.getTranslationString (m_FileLabelKey));
 	
    m_FileName = new JTextField ("",32);
    m_FileName.setBackground (Color.white);
    m_FileName.addActionListener (this);
 	
    m_BrowseButton = new JButton (Translatrix.getTranslationString ("BrowseButton"));
    m_BrowseButton.addActionListener (this);
     
    this.relocalize();
    
    this.add (m_FileLabel,  l_Constraints.xywh(2, 2, 3, 1));
	this.add (m_FileName,  		l_Constraints.xywh(2, 4, 1, 1));
	this.add (m_BrowseButton,  	l_Constraints.xywh(4, 4, 1, 1));
   
    switch (p_Mode)
        {
	case c_ForLoading   : 
	case c_ForSaving    :
	case c_ChooseFolder : m_Mode = p_Mode;
	                      break;
	default             : m_Mode = c_ForLoading;
	}
            
    m_FilePath      = "";
    m_ChosenFile    = null; 
    
    if (!(m_LastDirectory instanceof File))
        {
        try {
            m_LastDirectory = new File (System.getProperty ("user.dir"));
            }
        catch (SecurityException l_Exception)
            {
            m_LastDirectory = new File ("","");
            }
        }
    }

//***************************************************************************
//* Class Primitives                                                        *
//***************************************************************************

public static void localizeFileSelector ()
    {
    //---Labels ----------------------------------------------------------------
       
    UIManager.put ("FileChooser.lookInLabelText",           
                    Translatrix.getTranslationString ("FileSelector.LookIn"));
    UIManager.put ("FileChooser.saveInLabelText",           
                    Translatrix.getTranslationString ("FileSelector.SaveIn"));
    UIManager.put ("FileChooser.fileNameLabelText",           
                    Translatrix.getTranslationString ("FileSelector.FileName"));
    UIManager.put ("FileChooser.filesOfTypeLabelText",
                    Translatrix.getTranslationString ("FileSelector.FilesOfType"));
     
    //--- Detail Headers -------------------------------------------------------
    
    UIManager.put ("FileChooser.fileNameHeaderText",
                    Translatrix.getTranslationString ("FileSelector.FileNameHeader"));
    UIManager.put ("FileChooser.fileSizeHeaderText",
                    Translatrix.getTranslationString ("FileSelector.FileSizeHeader"));
    UIManager.put ("FileChooser.fileTypeHeaderText",
                    Translatrix.getTranslationString ("FileSelector.FileTypeHeader"));
    UIManager.put ("FileChooser.fileDateHeaderText",
                    Translatrix.getTranslationString ("FileSelector.FileDateHeader"));
    UIManager.put ("FileChooser.fileAttrHeaderText",
                    Translatrix.getTranslationString ("FileSelector.FileAttributesHeader"));

    //--- Buttons --------------------------------------------------------------
    
    UIManager.put ("FileChooser.saveButtonText",
                    Translatrix.getTranslationString ("FileSelector.SaveButton"));
    UIManager.put ("FileChooser.openButtonText",
                    Translatrix.getTranslationString ("FileSelector.OpenButton"));
    UIManager.put ("FileChooser.directoryOpenButtonText",
                    Translatrix.getTranslationString ("FileSelector.DirectoryOpenButton"));
    UIManager.put ("FileChooser.cancelButtonText",
                    Translatrix.getTranslationString ("FileSelector.CancelButton"));
    UIManager.put ("FileChooser.updateButtonText",
                    Translatrix.getTranslationString ("FileSelector.UpdateButton"));
    UIManager.put ("FileChooser.helpButtonText",
                    Translatrix.getTranslationString ("FileSelector.HelpButton"));
    
    //--- Tooltips ------------------------------------------------------------
   
    UIManager.put ("FileChooser.upFolderToolTipText",
                    Translatrix.getTranslationString ("FileSelector.UpFolderTip"));
    UIManager.put ("FileChooser.homeFolderToolTipText",
                    Translatrix.getTranslationString ("FileSelector.HomeFolderTip"));   
    UIManager.put ("FileChooser.newFolderToolTipText",
                    Translatrix.getTranslationString ("FileSelector.NewFolderTip"));
    UIManager.put ("FileChooser.listViewButtonToolTipText",
                    Translatrix.getTranslationString ("FileSelector.ListViewTip"));
    UIManager.put ("FileChooser.detailsViewButtonToolTipText",
                    Translatrix.getTranslationString ("FileSelector.DetailViewTip"));
    UIManager.put ("FileChooser.saveButtonToolTipText",
                    Translatrix.getTranslationString ("FileSelector.SaveButtonTip"));
    UIManager.put ("FileChooser.openButtonToolTipText",
                    Translatrix.getTranslationString ("FileSelector.OpenButtonTip"));
    UIManager.put ("FileChooser.cancelButtonToolTipText",
                    Translatrix.getTranslationString ("FileSelector.CancelButtonTip"));
    UIManager.put ("FileChooser.updateButtonToolTipText",
                    Translatrix.getTranslationString ("FileSelector.UpdateButtonTip"));
    UIManager.put ("FileChooser.helpButtonToolTipText",
                    Translatrix.getTranslationString ("FileSelector.HelpButtonTip"));
    }

//***************************************************************************
//* Class Body                                                              *
//***************************************************************************

//---------------------------------------------------------------------------
/** sets the FileFilter to be used in the "Browse" FileChooser.
 * @param p_FileFilter specifies the file filter to be used. Specify <CODE>null</CODE> to disable previously set
 * File filter
 */
//---------------------------------------------------------------------------

public void setFileFilter (FileFilter   p_FileFilter)
    {
    m_FileFilter = p_FileFilter;
    }    
        
//---------------------------------------------------------------------------
/** overwrites ActionListener's actionPerformed method. Method responds to Buttons
 * and changes in TextField.
 * @param p_ActionEvent the action event triggering method invocation
 */
//---------------------------------------------------------------------------

public void	actionPerformed (ActionEvent p_Event)
    {
    int         l_Choice;
	
    if (p_Event.getSource () == m_BrowseButton)
        {
        JFileChooser  l_FileSelector = new JFileChooser (m_LastDirectory);
        l_FileSelector.setLocale (Translatrix.getLocale());
        l_FileSelector.setOpaque(false); 
        
        if (m_FileFilter != null)
        	l_FileSelector.setFileFilter (m_FileFilter);
            
        if (m_ChosenFile instanceof File) 
        	{
            l_FileSelector.setSelectedFile(m_ChosenFile);
            }
        else if (m_LastDirectory instanceof File)
            {
        	l_FileSelector.setCurrentDirectory (m_LastDirectory);
            }
				    
        switch (m_Mode)
        	{
			case c_ForLoading   : l_FileSelector.setDialogTitle (Translatrix.getTranslationString ("FileSelectorPanel.LoadFileTitle"));
	                              l_Choice = l_FileSelector.showOpenDialog (m_Owner);
	                              break;
	
			case c_ForSaving    : l_FileSelector.setDialogTitle (Translatrix.getTranslationString ("FileSelectorPanel.SaveFileTitle"));
					      		  l_Choice = l_FileSelector.showSaveDialog (m_Owner);
	                              break;
	
			case c_ChooseFolder : l_FileSelector.setDialogTitle (Translatrix.getTranslationString ("FileSelectorPanel.ChooseFolderTitle"));
	                              l_FileSelector.setFileSelectionMode (JFileChooser.DIRECTORIES_ONLY);
	                              l_Choice = l_FileSelector.showDialog (m_Owner,Translatrix.getTranslationString ("FileSelectorPanel.ChooseButton"));
	                              break;
	
			default             : l_FileSelector.setDialogTitle (Translatrix.getTranslationString ("FileSelectorPanel.LoadFileTitle"));
	                              l_Choice = l_FileSelector.showOpenDialog (m_Owner);
	                              break;
            }
                
        if (l_Choice == JFileChooser.APPROVE_OPTION)
        	{
            File l_OldFile = m_ChosenFile;
            m_ChosenFile = l_FileSelector.getSelectedFile ();
            m_FilePath   = m_ChosenFile.getParent ();
            m_FileName.setText (m_ChosenFile.getName ());
            firePropertyChange (c_FileSelectionChanged,l_OldFile,m_ChosenFile);
            m_LastDirectory = m_ChosenFile;
            }
        }
   else if (p_Event.getSource () == m_FileName)
        {
        File l_OldFile = m_ChosenFile;
        if ( ((String)m_FileName.getText ()).length () > 0)
            {
            m_ChosenFile = new File (m_FilePath, m_FileName.getText ());
            }
        else m_ChosenFile = null;

        firePropertyChange (c_FileSelectionChanged,l_OldFile,m_ChosenFile);           
        }
    }

//***************************************************************************
//* Class Body		                                                    *
//***************************************************************************

//---------------------------------------------------------------------------
/** switches the enabled state of the filename textfield and the browse button
 * @param p_EnableIt setting p_EnableIt to <CODE>true</CODE> will enable the file selector panel, <CODE>false</CODE> will
 * disable it.
 */
//---------------------------------------------------------------------------

public void setEnabled (boolean p_EnableIt)
    {
    super.setEnabled (p_EnableIt);
	m_FileLabel.setEnabled(p_EnableIt);
    m_FileName.setEnabled(p_EnableIt);
    m_BrowseButton.setEnabled(p_EnableIt);
    }    
    
//---------------------------------------------------------------------------
/** returns the currently chosen file if any, <CODE>null</CODE> otherwise
 * @return the currently chosen file if any, <CODE>null</CODE> otherwise
 */
//---------------------------------------------------------------------------

public File getChosenFile ()
    {
    return (m_ChosenFile);
    }
    
//---------------------------------------------------------------------------
/** resets the currently chosen file. */
//---------------------------------------------------------------------------

public void forgetFile ()
    {
    m_ChosenFile = null;
    m_FilePath   = "";
    m_FileName.setText ("");
    }

//---------------------------------------------------------------------------
/** sets the currently chosen file to the one specified by p_File
 * @param p_File specifies the file to be set as chosen file.
 */
//---------------------------------------------------------------------------

public void setFile (File p_File)
    {
    if (p_File instanceof File)
        {
        m_ChosenFile = p_File;
        m_FilePath   = m_ChosenFile.getParent ();
        m_FileName.setText (m_ChosenFile.getName ());
        }        
    else
        {
        m_ChosenFile = null;
        m_FilePath   = "";
        m_FileName.setText ("");
        }
    }
    
/**
 * sets teh working dir of the filechooser
 * @param dir
 */
public void setDir(File dir) {
    m_LastDirectory = dir;
}

//---------------------------------------------------------------------------
/** Returns the full path to the currently chosen file.
 * @return the full path to the currently chosen file.
 */
//---------------------------------------------------------------------------

public String getFilePath ()
    {
    return (m_FilePath + "/" + m_FileName.getText ());
    }

//---------------------------------------------------------------------------
/**
 * Method is part of the Relocalizable interface. The method does everything
 * required to reflect changes of active Locale
 */
//---------------------------------------------------------------------------

public void relocalize() 
    {
    if (m_BrowseButton != null)
        m_BrowseButton.setText (Translatrix.getTranslationString ("FileSelectorPanel.BrowseButton"));
 
    if (m_FileLabel != null)
    	m_FileLabel.setText (Translatrix.getTranslationString (m_FileLabelKey));
  
    SwingLocalizer.localizeJFileChooser();
    }

public void setEditable(boolean b) {
	this.m_BrowseButton.setEnabled(b);
	this.m_FileName.setEditable(b);
}

//***************************************************************************
//* End of Class															*
//***************************************************************************
}


