/*===========================================================================
EDIT HISTORY
wjr		01/09/02	created wepsPropertyChangeListener
===========================================================================*/
/**
 * WepsFileChooser<p>
 * This class is based on the JFileChooser dialog and handles
 * opening a WEPS project by displaying any WEPS project directory
 * with a special icon. If the user double-clicks a WEPS project
 * directory than it returns the name of the directory (does not
 * descend into the directory).<p>
 * To display weps projects the dialog should be setup and called as
 * in the following example:
 *      WepsFileChooser chooser = new WepsFileChooser();
 *      	// navigate to whereever the default projects reside
 *      File curDir = new File("c:\\");
 *      chooser.setCurrentDirectory(curDir);
 *      int result = chooser.showOpenDialog(null);
 *      if (result == JFileChooser.APPROVE_OPTION) {
 *            	* work with the picked item
 *            JOptionPane msg = new JOptionPane();
 *            msg.showMessageDialog(null,
 *            chooser.getSelectedFile().getAbsolutePath(),"WEPS
 *            Project Picked",JOptionPane.PLAIN_MESSAGE);
 *      }
 * To change the icon that is displayed next to a project modify the
 * file images/smweru.gif or change the name of the file to load.
 *
 * @author Jim Frankenberger, USDA-ARS NSERL, August 2001
 */
/*===========================================================================
EDIT HISTORY of McrewFileChooser.java--now WepsFileChooser.java
wjr		01/09/02	created McrewPropertyChangeListener
sudhir          01/12/02        added the management and operation functionality
made code more readable and added some comments
sada            04/01/03        changed the class to Mcrewfilechooser which is stripped down version of wepsfileChooser +
functionality to open XML files (man xml files, Operation and crop xml files).
neha            07/09/04        merged McrewFileChooser.java and WepsFileChooser.java  so that Mcrew uses
WepsFileChooser. McrewFileChooser.java has been removed.
===========================================================================*/
package usda.weru.util;

import de.schlichtherle.io.File;
import de.schlichtherle.io.swing.FileSystemView;
import de.schlichtherle.io.swing.JFileChooser;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.FileNotFoundException;
import java.lang.reflect.Field;
import java.util.Hashtable;
import java.util.Locale;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileFilter;

import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.wsdl.extensions.ExtensionSerializer;
import org.apache.log4j.Logger;
import sun.awt.shell.ShellFolder;
import sun.swing.FilePane;
import usda.weru.resources.Resources;
import usda.weru.weps.RunFileData;

public class WepsFileChooser extends JFileChooser implements PropertyChangeListener, DocumentListener {
    private final Logger LOGGER = Logger.getLogger(WepsFileChooser.class);
    /**
     * File types supported by WepsFileChooser
     */
    public static final int PROJECT=0;
    public static final int RUN=1;
    public static final int MANAGE=2;
    public static final int SOIL=3;
    public static final int OPERATION=4;
    public static final int WIND=5;
    public static final int CLIMATE=6;
    public static final int XML=7;
    public static final int CROP=8;
    public static final int GENERAL=9;
    public static final int PROJDIR=10;
    public static final int DIR=11;
    public static final int SOILDB=12;
    public static final int EXE=13;
    public static final int SWEEP=14;
    public static final int WINDIDX=15;       
    public static final int WINDDB=16;
    public static final int CLIIDX=17;        
    public static final int CLIDB=18;
    public static final int LOG=19;
    //Special case for a general accept all sort of thing
    public static final int FILE=20;
    public static final int RUNDIR=21;
    public static final int DB=22;
    public static final int SHAPE=23;
    public static final int DAT=24;
    public static final int ROT=25;
    
        
    /**
     * Actions supported by WepsFileChooser
     */
    public static final int OPEN=0;
    public static final int SAVE=1;
    public static final int DELETE=2;
    public static final int CREATE=3;
    public static final int SELECT=4;
    
    public static enum Action{
        Open(OPEN),
        Save(SAVE),
        Delete(DELETE),
        Create(CREATE),
        Select(SELECT);
        private final int legacyId;

        private Action(int id) {
            this.legacyId = id;
        }        
        
    }
    
    private int type;
    private int action;
    private String homeDirPath;
    private boolean newFlg;
    private boolean persitSelectedFile;
    private JTextField dialogTextField;
    private String oldFileName="";
    private boolean forceEdit=false;
    private static final String[] buttonText={"Open", "Save", "Delete", "Create", "Select"};
    private static final String[] actions={"Open a ", "Save a ", "Delete a ", "Create a ", "Select a "};
    private static final String[][] prompts={{"WEPS project", "WEPS Project"},
        {"WEPS simulation run", "WEPS Simulation Run"},
        {"management file", "Management File"},
        {"soilzzz file", "Soil File"},
        {"operation file", "Operation File"},
        {"wind file", "Wind File"},
        {"climate file", "Climate File"},
        {"XML file", "XML File"},
        {"crop file", "Crop File"},
        {"management file", "Management Files(*.man,*.xml)"},
        {"WEPS Project Directory", "WEPS Project Directory"},
        {"Directory", "Directory"},
        {"Soil Database File(.mdb)", "Soil Database File(.mdb)"},
        {"Executable File", "Executable File"},
        {"SWEEP Run", "SWEEP Run"},
        {"Wind Index", "Wind Index"},
        {"Wind Database", "Wind Database"},
        {"Climate Index", "Climate Index"},
        {"Climate Database", "Climate Database"},
        {"Log File", "Log File (*.log)"},
        {"File", "File"},
        {"WEPS Run Directory Location", "WEPS Run Directory Location"},
        {"Database", "Database"},
        {"Shapefile", "Shapefile"},
        {"Data File", "Data File"},
        {"Rotation File", "Rotation File"}
          };
    
    private	static	final	String[]	fileExts = {".wpj", ".wjr", ".man", ".ifc", ".oprn", ".win", ".cli", ".xml",
        ".crop", ".man", ".*", ".*", ".mdb", ".exe", ".in", ".idx", ".wdb", ".idx", ".par", ".log", "", ".*", ".db", ".shp","dat","rot"
    };
    //Filter for directories when the type is SOILDB
    WepsFileFilter soilFilter;
    
    private static String iconNames[]={"folderp.gif", "folderR.gif", "fileM.gif", "fileS.gif", "fileO.gif", "windIcon", "cliIcon", "xmlicon", "fileC.gif"};
    private static Icon wepsIconPrj;
    private static Icon wepsIconRun;
    private static Icon wepsIconMan;
    private static Icon wepsIconIFC;
    private static Icon wepsIconOpn;
    private static Icon wepsIconCrop;
    private static Icon wepsIconFdr;
    private static Icon mcrewIconXML;
    private static Icon wepsIconShape;
    private static Icon wepsIconRot;

    static {
        wepsIconPrj = Resources.getIcon(iconNames[WepsFileChooser.PROJECT]);
        wepsIconRun=Resources.getIcon(iconNames[WepsFileChooser.RUN]);
        wepsIconMan=Resources.getIcon(iconNames[WepsFileChooser.MANAGE]);
        wepsIconIFC=Resources.getIcon(iconNames[WepsFileChooser.SOIL]);
        wepsIconOpn=Resources.getIcon(iconNames[WepsFileChooser.OPERATION]);
        wepsIconCrop=Resources.getIcon(iconNames[WepsFileChooser.CROP]);
        wepsIconFdr=Resources.getIcon("folder.gif");
        wepsIconShape=Resources.getIcon("folderShape.gif");
        wepsIconRot = Resources.getIcon("fileR.gif");
        
    }
    
    private static Hashtable<String, Integer> HT_propertyToType = new Hashtable<String, Integer>();
    
    static {
        HT_propertyToType.put(ConfigData.WepsExe, Integer.valueOf(EXE));
        HT_propertyToType.put(ConfigData.CliExe, Integer.valueOf(EXE));
        HT_propertyToType.put(ConfigData.WinExe, Integer.valueOf(EXE));
        HT_propertyToType.put(ConfigData.WindInterp1EXE, Integer.valueOf(EXE));
        HT_propertyToType.put(ConfigData.WindInterp2EXE, Integer.valueOf(EXE));
        HT_propertyToType.put(ConfigData.SWEEPExe, Integer.valueOf(EXE));
        HT_propertyToType.put(ConfigData.WinData, Integer.valueOf(WINDDB));
        HT_propertyToType.put(ConfigData.WinIndex, Integer.valueOf(WINDIDX));
        HT_propertyToType.put(ConfigData.CliData, Integer.valueOf(CLIDB));
        HT_propertyToType.put(ConfigData.CliIndex, Integer.valueOf(CLIIDX));
        HT_propertyToType.put(ConfigData.ManTemp, Integer.valueOf(DIR));
        HT_propertyToType.put(ConfigData.ManTempSaveAs, Integer.valueOf(DIR));
        HT_propertyToType.put(ConfigData.ManSkel, Integer.valueOf(DIR));
        HT_propertyToType.put(ConfigData.ManDB, Integer.valueOf(DIR));
        HT_propertyToType.put(ConfigData.CropDB, Integer.valueOf(DIR));
        HT_propertyToType.put(ConfigData.MCREW, Integer.valueOf(DIR));
        HT_propertyToType.put(ConfigData.SoilDB, Integer.valueOf(DIR));
        HT_propertyToType.put(ConfigData.ProjDir, Integer.valueOf(DIR));
        HT_propertyToType.put(ConfigData.DefaultRunsLocationTemplate, Integer.valueOf(DIR));
        HT_propertyToType.put(ConfigData.McrewDataConfigFile, Integer.valueOf(DIR));
        HT_propertyToType.put(ConfigData.SkelTranslationFile, Integer.valueOf(FILE));
        HT_propertyToType.put(ConfigData.ReportFileName, Integer.valueOf(FILE));
        HT_propertyToType.put(ConfigData.DetailTableFilterFile, Integer.valueOf(FILE));
        HT_propertyToType.put(ConfigData.GISData, Integer.valueOf(DIR));
        HT_propertyToType.put(ConfigData.SoilOrganicFile, Integer.valueOf(SOIL));
        HT_propertyToType.put(ConfigData.BarriersFile, Integer.valueOf(FILE));
        HT_propertyToType.put(ConfigData.CurrentProj, Integer.valueOf(PROJECT));
        HT_propertyToType.put(ConfigData.FuelDatabase, Integer.valueOf(XML));
        
    }
    public WepsFileChooser(String property, int action) {        
        try {
            int type = HT_propertyToType.get(property).intValue();
            init(type, ".", action);
        
        } catch (NullPointerException npe) {
            System.err.println("WFC: property not defined " + property);;
            init(FILE, ".", action);
        }
    }
    
    public static WepsFileChooser create(Action action, File home, FileType type){
        return create(action, home, false, false,  null, type);
    }
    
    public static WepsFileChooser create(Action action, File home, boolean allFilter, boolean groupFilter, String groupName, FileType... types){
        WepsFileChooser chooser = new WepsFileChooser();
        
        chooser.persitSelectedFile = action == Action.Save;
        
        //use the first type in the array
        chooser.type = -1;
        chooser.action = action.legacyId;
        chooser.homeDirPath = home != null ? home.getAbsolutePath() : "";
        
        WepsFileSystemView view = WepsFileSystemView.getDefault();
        view.setHomeDir(chooser.homeDirPath);
        FileSystemView fsv = (FileSystemView) FileSystemView.getFileSystemView();        
        fsv.setDelegate(view);
        chooser.setFileSystemView(fsv);
        
        chooser.newFlg = action == Action.Save || action == Action.Create;
        
        

        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        boolean dirs = false;
        boolean files = false;
        for(FileType type: types){
            if(type.acceptsFiles()){
                files = true;
            }
            if(type.acceptsDirectories()){
                dirs = true;
            }                        
        }
        
        if(dirs && files){
            chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);            
        }
        else if (files){
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        }
        else if (dirs){
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        }
                        
        FileFilter all = chooser.getAcceptAllFileFilter();
        chooser.removeChoosableFileFilter(all);        
        
        FileFilter group = null;
        if(groupFilter){
            final String name = groupName != null ? groupName : "Supported Files";
            final FileFilter[] filters = new FileFilter[types.length];
            StringBuilder extensionList = new StringBuilder();
            for(int i = 0; i < types.length; i++){
                filters[i] = types[i].getFileFilter();
                extensionList.append("*");
                extensionList.append(types[i].getExtension());
                if(i + 1 < types.length){
                    extensionList.append(", ");
                }
            }
            final String extensions = extensionList.toString();            
            group = new FileFilter() {

                @Override
                public boolean accept(java.io.File file) {
                    if(file.isDirectory()){
                        return true;
                    }
                    for(FileFilter filter : filters){
                        if(filter.accept(file)){
                            return true;
                        }
                    }
                    return false;
                }

                @Override
                public String getDescription() {
                    return String.format("%s (%s)", name, extensions);
                }
            };
            chooser.addChoosableFileFilter(group);
        }
                        
        for(FileType type : types){            
            chooser.addChoosableFileFilter(type.getFileFilter());
        }
        
        if(allFilter){
           chooser.addChoosableFileFilter(all);             
        }
        
        //set the default filter
        if(group != null){
            chooser.setFileFilter(group);
        }
        else{
            //first user supplied
            chooser.setFileFilter(types[0].getFileFilter());
        }
        
        return chooser;
    }
    
    
    
    private WepsFileChooser(){
        
    }
    /**
     *
     * @param type
     * @param homeDirPath
     * @param action
     */
    public WepsFileChooser(int type, String homeDirPath, int action) {
        super();
        //Persit if we use the save action
        init(type, homeDirPath, action);
    }
    
    private void init(int type, String homeDirPath, int action) {        
        if (action == SAVE) {
            persitSelectedFile=true;
        } else {
            persitSelectedFile=false;
        }
        Util.debugPrint(true, homeDirPath);
        this.type=type;
        this.action=action;
        this.homeDirPath=homeDirPath;
        
        WepsFileSystemView view = WepsFileSystemView.getDefault();
        view.setHomeDir(homeDirPath);
        FileSystemView fsv = (FileSystemView) FileSystemView.getFileSystemView();        
        fsv.setDelegate(view);
        setFileSystemView(fsv);
        
        //setFileSystemView(view);
        
        newFlg=(action == SAVE) || (action == CREATE);
        
//        WepsFileSystemView myFileSystemView = new WepsFileSystemView(type,homeDirPath);
//        setFileSystemView(myFileSystemView);

        if (type != FILE) {
            removeChoosableFileFilter(getAcceptAllFileFilter());
        }

        setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

        setApproveButtonToolTipText(actions[action] + prompts[type][0]);
        setDialogTitle(actions[action] + prompts[type][1]);

        if (type == SOILDB) {
            soilFilter=new WepsFileFilter(DIR, action);
            addChoosableFileFilter(soilFilter);
            addChoosableFileFilter(new WepsFileFilter(SOILDB, action));
            addChoosableFileFilter(new WepsFileFilter(DB, action));
            setFileFilter(soilFilter);
        }

        if (type == MANAGE) {
            

            if(ConfigData.getDefault().isFormatXMLAllowed()){
                if (getDialogType() == JFileChooser.OPEN_DIALOG) {
                    WepsFileFilter generalFilter=new WepsFileFilter(GENERAL, action);
                    addChoosableFileFilter(generalFilter);
                //  setFileFilter(generalFilter);
                }

                WepsFileFilter xmlFilter=new WepsFileFilter(XML, action);
                addChoosableFileFilter(xmlFilter);
            }
            //Adding at the end so that this becomes the default selection in the FileChooser
            WepsFileFilter manFilter=new WepsFileFilter(MANAGE, action);
            addChoosableFileFilter(manFilter);
        } else {
            if (type != FILE && type != SOILDB) {
                WepsFileFilter filter=new WepsFileFilter(type, action);
                addChoosableFileFilter(filter);
                setFileFilter(filter);
            }
        }




        addPropertyChangeListener(this);
        dialogTextField=(JTextField) findJTextField(this);
        if (dialogTextField != null) {
            dialogTextField.getDocument().addDocumentListener(this);
            ((AbstractDocument) dialogTextField.getDocument()).setDocumentFilter(new PersitFileNameFilter());
        }


    }


     //START TRUEZIP/SHELFOLDER HACKS

    @Override
     public void setCurrentDirectory(java.io.File dir) {
        if(dir != null && dir.getName().equals(getCurrentDirectory().getName())){
            return;
        }
        else{
            super.setCurrentDirectory(dir);
        }

    }

     @Override
    public void updateUI() {
        super.updateUI();


        //hack the combo box, turn shell folder use on
        try{
            Field useShellFolderField = getUI().getClass().getDeclaredField("useShellFolder");
            useShellFolderField.setAccessible(true);
            useShellFolderField.setBoolean(getUI(), true);
        }
        catch(Exception e){
            LOGGER.warn("Unable to set useShellFolder to true.", e);
        }


        //Hack to fix truezip/shellfolder bickering
        final FilePane fp = Util.findFirstDecendent(this, FilePane.class);

        final MouseListener handler = new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent evt) {

                if (SwingUtilities.isLeftMouseButton(evt) && (evt.getClickCount() % 2 == 0)) {

                        File selectedFile = (File) getSelectedFile();
                        if(selectedFile == null){
                            return;
                        }
                        //test if shellfolder doesn't like the file
                        try {
                            Object shell = ShellFolder.getShellFolder(selectedFile);
                        }
                        catch (FileNotFoundException e) {
                            //ShellFolder did not like the file, so we force the selection
                            if (isTraversable(selectedFile)) {
                                setCurrentDirectory(selectedFile);
                            }
                            else {
                                approveSelection();
                            }
                        }
                }
            }
        };

        //install the listeners when ever this changes
        fp.addPropertyChangeListener("viewType", new PropertyChangeListener() {

            public void propertyChange(PropertyChangeEvent evt) {
                installHackListener(fp, handler);
            }
        });

        installHackListener(fp, handler);



    }

    private void installHackListener(FilePane fp, MouseListener handler){
        final JList list = Util.findFirstDecendent(fp, JList.class);
        final JTable details = Util.findFirstDecendent(fp, JTable.class);
        if (list != null) {
            //install list view listener
            list.removeMouseListener(handler);
            list.addMouseListener(handler);
        }

        if(details != null){
            //install details view listener
            details.removeMouseListener(handler);
            details.addMouseListener(handler);
        }
    }



    //END TRUEZIP/SHELFOLDER HACKS
    
    public File lookupDefaultDirectory(String name){

        //a few tricky cases, when MCREW_CFG should be the parent
        if(ConfigData.SkelTranslationFile.equals(name) || ConfigData.McrewDataConfigFile.equals(name)){
            String path = ConfigData.getDefault().getDataParsed(ConfigData.MCREW);
            if (path != null){
                return new File(path);
            }            
        }
        else{
            ConfigData.FileConfigurationOption option = ConfigData.getDefault().getFileConfigurationOption(name);
            if(option != null){
                String path = option.defaultLocation();
                if(path != null && path.length() > 0){
                    return new File(path);
                }
            }
        }

        //last case
        return null;
    }

    public void setDefaultCurrentDirectory(String name){
        File dir = lookupDefaultDirectory(name);
        if(dir != null){
            setCurrentDirectory(dir);
        }
    }

   
    
    public static String getFileExtension(int index){
        return fileExts[index];
    }

    @Override
    public Icon getIcon(java.io.File file) {
        if (file.getName().toLowerCase().endsWith(WepsFileChooser.fileExts[WepsFileChooser.MANAGE])) {
            if (wepsIconMan.getIconHeight() >= 0 && wepsIconMan.getIconWidth() >= 0) {
                return wepsIconMan;
            }
        }
        
        if (WepsFileTypes.Rotation.accept(file)){
            if (wepsIconRot.getIconHeight() >= 0 && wepsIconRot.getIconWidth() >= 0) {
                return wepsIconRot;
            }
        }

        if (file.getName().toLowerCase().endsWith(WepsFileChooser.fileExts[WepsFileChooser.RUN])) {
            if (wepsIconRun.getIconHeight() >= 0 && wepsIconRun.getIconWidth() >= 0) {
                return wepsIconRun;
            }
        }
        if (file.getName().toLowerCase().endsWith(WepsFileChooser.fileExts[WepsFileChooser.PROJECT])) {
            if (wepsIconPrj.getIconHeight() >= 0 && wepsIconPrj.getIconWidth() >= 0) {
                return wepsIconPrj;
            }
        }

        if (file.getName().toLowerCase().endsWith(WepsFileChooser.fileExts[WepsFileChooser.SOIL])) {
            if (wepsIconIFC.getIconHeight() >= 0 && wepsIconIFC.getIconWidth() >= 0) {
                return wepsIconIFC;
            }
        }
        if (file.getName().toLowerCase().endsWith(WepsFileChooser.fileExts[WepsFileChooser.OPERATION])) {
            if (wepsIconOpn.getIconHeight() >= 0 && wepsIconOpn.getIconWidth() >= 0) {
                return wepsIconOpn;
            }
        }

        if (file.getName().toLowerCase().endsWith(WepsFileChooser.fileExts[WepsFileChooser.CROP])) {
            if (wepsIconCrop.getIconHeight() >= 0 && wepsIconCrop.getIconWidth() >= 0) {
                return wepsIconCrop;
            }
        }
        
        if (file.isDirectory()) {
            File sFile = new File(file);
            String dirName = sFile.getName();
            String[] fileNames = (dirName.length() > 0) ? sFile.list() : null;
            if (fileNames != null) {
                boolean dbfFlg = false;
                boolean shpFlg = false;
                for (String name : fileNames) {
                    if (name.startsWith(dirName) && name.endsWith(".dbf")) {
                        dbfFlg = true;
                    }
                    if (name.startsWith(dirName) && name.endsWith(".shp")) {
                        shpFlg = true;
                    }
                    if (dbfFlg && shpFlg) {
                        return wepsIconShape;
                    }
                }
            }
        }
        return super.getIcon(file);
    }
    
    

    class PersitFileNameFilter extends DocumentFilter {
        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
            super.insertString(fb, offset, string, attr);
        }

        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            if (persitSelectedFile && !forceEdit && !dialogTextField.hasFocus()) {
                super.replace(fb, offset, oldFileName.length(), oldFileName, attrs);
            } else {
                super.replace(fb, offset, length, text, attrs);
            }
        }
    }

    /**
     *
     * @param pTypeName
     * @return
     */
    public static int getType(String pTypeName) {

        if (pTypeName == null) {
            //System.err.println("WepsFileChooser:getType: " + " NullPointerException");
            return -1;
        }

        if (!pTypeName.startsWith(".")) {
            pTypeName="." + pTypeName;
        }

        for (int idx=0; idx < fileExts.length; idx++) {
            if (pTypeName.toLowerCase().equals(fileExts[idx])) {
                return idx;
            }
        }

        //System.err.println("WFC_gT: pTypeName >" + pTypeName + "<");
        return 0;
    }

    public boolean getPersitSelectedFile() {
        return persitSelectedFile;
    }

    public void setPersitSelectedFile(boolean persit) {
        persitSelectedFile=persit;
    }

    /**
     *
     * @param parent
     * @return
     */
    public int showDialog(Component parent) {
        return showDialog(parent, buttonText[action]);

    }

    // checks for a weps project directory and closes the window if the user
    //is trying to "open" a weps project directory
    public void approveSelection() {
        try {
            File dir=new File(getSelectedFile().getAbsolutePath());
            File runfile=dir;
            if (newFlg) {		// any file name is accepted for new
                if (dir.exists()) {
                    JOptionPane.showMessageDialog(this, dir.getName() + " already exists.\nPlease choose another file name.", "WEPS", JOptionPane.WARNING_MESSAGE);
                    return;
                } else if (dir.getInnerArchive() != null) {
                    //This file would be in an archive, Naughty You!!
                    JOptionPane.showMessageDialog(this, "Archives are read-only.\nPlease choose another file location.", "WEPS", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                super.approveSelection();
            } else {
                if (runfile != null) {
                    //If type is PROJDIR/DIR/RUNDIR means that we are just selecting
                    //a (project) directory here and this is not a file type
                    if ((type == PROJDIR || type == DIR || type == RUNDIR) && runfile.canRead()) {
                        super.approveSelection();
                    }                    
                    //If the type is SOILDB and the currently selected filter is
                    //soilSilter, then approve the selection (directory) - neha
                    else if (type == SOILDB) {
                        super.approveSelection();
                    }
                    else if (type == MANAGE && runfile.canRead() && (runfile.getName().toLowerCase().endsWith(fileExts[type]) || runfile.getName().toLowerCase().endsWith(fileExts[XML]))) {
                        super.approveSelection();
                    }
                    else if (type == PROJECT && runfile.getName().toLowerCase().endsWith(RunFileData.ProjectSuffix) && dir.getInnerArchive() != null) {
                        JOptionPane.showMessageDialog(this, "Opening projects inside an archive is not allowed.\nPlease choose a different project.", "WEPS", JOptionPane.WARNING_MESSAGE);
                        return;
                    }    
                    else if(type == -1){
                        //new code
                        super.approveSelection();
                    }
                    else if (runfile.canRead() && runfile.getName().toLowerCase().endsWith(fileExts[type])) {
                        super.approveSelection();
                    }
                }
            }
            //If the user selects a Directory and hits "Select" button, then that
            //Directory should be opened by setting the current dir to that dir
            // except when we want to SELECT A DIRECTORY- neha
            if (action == SELECT && runfile.canRead() && runfile.isDirectory() && !typeIsDirectory(type)) {
                setCurrentDirectory(runfile);

            }
        } catch (Exception e) {
        //System.err.println("WepsFileChooser:approveSelection:"+e);
        }
    }

    private boolean typeIsDirectory(int type) {
        if (type == PROJDIR || type == DIR || type == RUNDIR) {
            return true;
        } else {
            return false;
        }
    }

    /**
     *
     * @param inpComp
     */
    public void disableNewFolder(Container inpComp) {

        Component[] compArry=inpComp.getComponents();
        if (compArry == null) {
            return;
        }
        if (compArry.length == 0) {
            return;
        }
        for (int i=0; i < compArry.length; i++) {
            if (compArry[i] == null) {
                continue;
            }
            if (compArry[i] instanceof JButton) {
                String temp=((JButton) compArry[i]).getToolTipText();
                if (temp != null && temp.equalsIgnoreCase("Create New Folder")) {
                    ((JButton) compArry[i]).setVisible(false);
                }
            }
            if (compArry[i] instanceof Container) {
                disableNewFolder((Container) compArry[i]);
            }
        }
    }

    /**
     *
     * @param jfc
     */
    public void homeToolTip(javax.swing.JFileChooser jfc) {
        java.util.Hashtable ht=new java.util.Hashtable();
        ht.put("Desktop", "Home");
        Util.loadToolTips(jfc, ht);
    }

    /**
     *
     * @param e
     */
    public void propertyChange(PropertyChangeEvent e) {
        // handle event if we are trying to double click a weps project directory
        if (e.getPropertyName().equals(JFileChooser.DIRECTORY_CHANGED_PROPERTY)) {
            //File dir = (File);
            File dir=new File(((java.io.File) e.getNewValue()).getAbsolutePath());
            if (dir == null) {
                return;
            }
            if (dir.getName().equals("")) {
                return;
            }
            if (type == PROJECT) {
                if (dir.getAbsolutePath().toLowerCase().endsWith(fileExts[PROJECT])) {
                    super.approveSelection();
                }
            }
            if (type == RUN) {
                if (dir.getAbsolutePath().toLowerCase().endsWith(fileExts[RUN])) {
                    super.approveSelection();
                }
            }
        }
        if (e.getPropertyName().equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY) || e.getPropertyName().equals(JFileChooser.DIRECTORY_CHANGED_PROPERTY)) {
            //We only do our persiting magic if we're told to.
            if (persitSelectedFile) {
                dialogTextField.setText(oldFileName);
            }
        }


    }

    private boolean toggle(boolean value) {
        return !value;
    }

    private void updateOldFileName() {
        if (dialogTextField.hasFocus() || forceEdit) {
            if (!oldFileName.equals(dialogTextField.getText())) {
                oldFileName=dialogTextField.getText();
            }
            forceEdit=false;
        }
    }

    public void changedUpdate(DocumentEvent de) {
        updateOldFileName();
    }

    public void insertUpdate(DocumentEvent de) {
        updateOldFileName();
    }

    public void removeUpdate(DocumentEvent de) {
        updateOldFileName();
    }

    private Component findJTextField(Component comp) {
        if (comp instanceof JTextField) {
            return comp;
        }
        if (comp instanceof Container) {
            Component[] components=((Container) comp).getComponents();
            for (int i=0; i < components.length; i++) {
                Component child=findJTextField(components[i]);
                if (child != null) {
                    return child;
                }
            }
        }
        return null;
    }

    public void setText(String text) {
        forceEdit=true;
        dialogTextField.setText(text);
    }

    public String getText() {
        return dialogTextField.getText();
    }


    
   


static class WepsFileFilter extends FileFilter {
    WepsFileFilter() {
        type=WepsFileChooser.PROJECT;
    }

    WepsFileFilter(int type, int action) {
        this.type=type;
//        this.action = action;

    }
//    private int action;
    private int type;

        @Override
    public boolean accept(java.io.File f) {

        /*
        if(type == WepsFileChooser.PROJDIR){
        //System.out.println("At Last");
        return true;
        }
         */
        // directories are always OK
        if (f.isDirectory()) {
            return true;
        }
        // files can be created anywhere
//        if (action == WepsFileChooser.SAVE || action == WepsFileChooser.CREATE) {
//            return true;
//        }

        //For "Open" and "Save As" for Management files, both .man and .xml should be accepted
        if (type == WepsFileChooser.GENERAL) {
            if (f.getName().toLowerCase().endsWith(WepsFileChooser.fileExts[WepsFileChooser.MANAGE])) {
                return true;
            } else if (f.getName().toLowerCase().endsWith(WepsFileChooser.fileExts[WepsFileChooser.XML])) {
                return true;
            }
            return false;
        }        
        // selecting, opening or deleting is allowed only on correct
        // type files
        if (f.getName().toLowerCase().endsWith(WepsFileChooser.fileExts[type])) {
            return true;
        }
        return false;
    }

    public String getDescription() {
        /**@todo: implement this javax.swing.filechooser.FileFilter abstract method*/
        try {
            if (type == WepsFileChooser.GENERAL) {
                return WepsFileChooser.prompts[WepsFileChooser.GENERAL][1];
            } else {
                return WepsFileChooser.prompts[type][1];
            }
        } catch (Exception e) {
            //System.out.println("Exception:"+e);
            return "type not set";
        }
    }

    public int getType() {
        return type;
    }
}


}//end of class WepsFileChooser