/*===========================================================================
 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.truezip.file.TFile;
import de.schlichtherle.truezip.file.swing.TFileSystemView;
import java.awt.Component;
import java.awt.Container;
import java.awt.HeadlessException;
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.util.HashMap;
import java.util.Map;
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.JFileChooser;
import javax.swing.JPanel;

import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import usda.weru.resources.Resources;
import usda.weru.weps.RunFileData;

/**
 *
 * @author maxerdwien
 */
public class WepsFileChooser extends JFileChooser implements PropertyChangeListener, DocumentListener {

    private static final long serialVersionUID = 1L;

    // TODO: implement a more graceful solution for these two things.
    // they are used in LocationPanel.java.
    public static Filetype CLIMATE = Filetype.CLIMATE;
    public static Filetype WIND = Filetype.WIND;

    /**
     * File types supported by WepsFileChooser
     * entry FILE is a special case to accept all files
     * entry ERROR does not represent a filetype, but a problem
     */
    public static enum Filetype {

        PROJECT, RUN, MANAGE, SOIL, OPERATION, WIND, CLIMATE, XML, CROP,
        GENERAL, PROJDIR, DIR, SOILDB, EXE, SWEEP, WINDIDX, WINDDB, CLIIDX, CLIDB, LOG, FILE,
        RUNDIR, DB, SHAPE, DAT, ROT, POL, ERROR
    };

    /**
     * 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 Filetype 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"},
    {"Polygon File", "Polygon 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", "pol"
    };
    //Filter for directories when the type is SOILDB
    WepsFileFilter soilFilter;

    private static final 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 wepsIconShape;
    private static Icon wepsIconRot;

    static {
        wepsIconPrj = Resources.getIcon(iconNames[WepsFileChooser.Filetype.PROJECT.ordinal()]);
        wepsIconRun = Resources.getIcon(iconNames[WepsFileChooser.Filetype.RUN.ordinal()]);
        wepsIconMan = Resources.getIcon(iconNames[WepsFileChooser.Filetype.MANAGE.ordinal()]);
        wepsIconIFC = Resources.getIcon(iconNames[WepsFileChooser.Filetype.SOIL.ordinal()]);
        wepsIconOpn = Resources.getIcon(iconNames[WepsFileChooser.Filetype.OPERATION.ordinal()]);
        wepsIconCrop = Resources.getIcon(iconNames[WepsFileChooser.Filetype.CROP.ordinal()]);
        wepsIconShape = Resources.getIcon("folderShape.gif");
        wepsIconRot = Resources.getIcon("fileR.gif");

    }

    private static final Map<String, Filetype> HT_propertyToType = new HashMap<String, Filetype>();

    static {
        HT_propertyToType.put(ConfigData.WepsExe, Filetype.EXE);
        HT_propertyToType.put(ConfigData.CliExe, Filetype.EXE);
        HT_propertyToType.put(ConfigData.WinExe, Filetype.EXE);
        HT_propertyToType.put(ConfigData.WindInterp1EXE, Filetype.EXE);
        HT_propertyToType.put(ConfigData.WindInterp2EXE, Filetype.EXE);
        HT_propertyToType.put(ConfigData.SWEEPExe, Filetype.EXE);
        HT_propertyToType.put(ConfigData.WinData, Filetype.WINDDB);
        HT_propertyToType.put(ConfigData.WinIndex, Filetype.WINDIDX);
        HT_propertyToType.put(ConfigData.CliData, Filetype.CLIDB);
        HT_propertyToType.put(ConfigData.CliIndex, Filetype.CLIIDX);
        HT_propertyToType.put(ConfigData.ManTemp, Filetype.DIR);
        HT_propertyToType.put(ConfigData.LocalManDB, Filetype.DIR);
        HT_propertyToType.put(ConfigData.ManSkel, Filetype.DIR);
        HT_propertyToType.put(ConfigData.SystemOpDB, Filetype.DIR);
        HT_propertyToType.put(ConfigData.SystemCropDB, Filetype.DIR);
        HT_propertyToType.put(ConfigData.MCREW, Filetype.DIR);
        HT_propertyToType.put(ConfigData.SoilDB, Filetype.DIR);
        HT_propertyToType.put(ConfigData.ProjDir, Filetype.DIR);
        HT_propertyToType.put(ConfigData.DefaultRunsLocationTemplate, Filetype.DIR);
        HT_propertyToType.put(ConfigData.McrewDataConfigFile, Filetype.DIR);
        HT_propertyToType.put(ConfigData.SkelTranslationFile, Filetype.FILE);
        HT_propertyToType.put(ConfigData.ReportFileName, Filetype.FILE);
        HT_propertyToType.put(ConfigData.DetailTableFilterFile, Filetype.FILE);
        HT_propertyToType.put(ConfigData.GISData, Filetype.DIR);
        HT_propertyToType.put(ConfigData.SoilOrganicFile, Filetype.SOIL);
        HT_propertyToType.put(ConfigData.BarriersFile, Filetype.FILE);
        HT_propertyToType.put(ConfigData.CurrentProj, Filetype.PROJECT);
        HT_propertyToType.put(ConfigData.FuelDatabase, Filetype.XML);
        HT_propertyToType.put(ConfigData.WindgenInterpolationBoundaryFile, Filetype.POL);

    }

    /**
     *
     * @param property
     * @param action
     */
    public WepsFileChooser(String property, int action) {
        try {
            Filetype thisFiletype = HT_propertyToType.get(property);
            init(thisFiletype, ".", action);

        } catch (NullPointerException npe) {
            System.err.println("WFC: property not defined " + property);
            init(Filetype.FILE, ".", action);
        }
    }

    /**
     *
     * @param action
     * @param home
     * @param type
     * @return
     */
    public static WepsFileChooser create(Action action, TFile home, FileType type) {
        return create(action, home, false, false, null, type);
    }

    /**
     *
     * @param action
     * @param home
     * @param allFilter
     * @param groupFilter
     * @param groupName
     * @param types
     * @return
     */
    public static WepsFileChooser create(Action action, TFile 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 = Filetype.ERROR;
        chooser.action = action.legacyId;
        chooser.homeDirPath = home != null ? home.getAbsolutePath() : "";

        WepsFileSystemView view = WepsFileSystemView.getDefault();
        view.setHomeDir(chooser.homeDirPath);
        TFileSystemView fsv = new TFileSystemView(view);
        //TFileSystemView fsv = (TFileSystemView) TFileSystemView.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(Filetype type, String homeDirPath, int action) {
        super();
        //Persit if we use the save action
        init(type, homeDirPath, action);
    }

    private void init(Filetype type, String homeDirPath, int action) {
        persitSelectedFile = action == SAVE;
        Util.debugPrint(true, homeDirPath);
        this.type = type;
        this.action = action;
        this.homeDirPath = homeDirPath;

        WepsFileSystemView view = WepsFileSystemView.getDefault();
        view.setHomeDir(homeDirPath);
        TFileSystemView fsv = new TFileSystemView(view);
        //TFileSystemView fsv = (TFileSystemView) TFileSystemView.getFileSystemView();
        //fsv.setDelegate(view);
        setFileSystemView(fsv);

        newFlg = (action == SAVE) || (action == CREATE);

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

        setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

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

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

        if (type == Filetype.MANAGE) {

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

                WepsFileFilter xmlFilter = new WepsFileFilter(Filetype.XML, action);
                addChoosableFileFilter(xmlFilter);
            }
            //Adding at the end so that this becomes the default selection in the FileChooser
            WepsFileFilter manFilter = new WepsFileFilter(Filetype.MANAGE, action);
            addChoosableFileFilter(manFilter);
        } else {
            if (type != Filetype.FILE && type != Filetype.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
    /**
     *
     * @param dir
     */
    @Override
    public void setCurrentDirectory(java.io.File dir) {
        if (dir == null || !dir.getName().equals(getCurrentDirectory().getName())) {
            super.setCurrentDirectory(dir);
        }
    }

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

        final JPanel fp = Util.findFirstDecendent(this, JPanel.class);

        final MouseListener handler = new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent evt) {

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

                    Object o = getSelectedFile();
                    TFile selectedFile = (TFile) o;
                    if (selectedFile == null) {
                    }
                }
            }
        };

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

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

        installHackListener(fp, handler);

    }

    private void installHackListener(JPanel 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
    /**
     *
     * @param name
     * @return
     */
    public TFile 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 TFile(path);
            }
        } else {
            ConfigData.FileConfigurationOption option = ConfigData.getDefault().getFileConfigurationOption(name);
            if (option != null) {
                String path = option.defaultLocation();
                if (path != null && path.length() > 0) {
                    return new TFile(path);
                }
            }
        }

        //last case
        return null;
    }

    /**
     *
     * @param name
     */
    public void setDefaultCurrentDirectory(String name) {
        TFile dir = lookupDefaultDirectory(name);
        if (dir != null) {
            setCurrentDirectory(dir);
        }
    }

    /**
     *
     * @param thisType
     * @return
     */
    public static String getFileExtension(Filetype thisType) {
        return fileExts[thisType.ordinal()];
    }

    /**
     *
     * @param file
     * @return
     */
    @Override
    public Icon getIcon(java.io.File file) {
        if (file.getName().toLowerCase().endsWith(
                WepsFileChooser.fileExts[WepsFileChooser.Filetype.MANAGE.ordinal()])) {
            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.Filetype.RUN.ordinal()])) {
            if (wepsIconRun.getIconHeight() >= 0 && wepsIconRun.getIconWidth() >= 0) {
                return wepsIconRun;
            }
        }
        if (file.getName().toLowerCase().endsWith(WepsFileChooser.fileExts[WepsFileChooser.Filetype.PROJECT.ordinal()])) {
            if (wepsIconPrj.getIconHeight() >= 0 && wepsIconPrj.getIconWidth() >= 0) {
                return wepsIconPrj;
            }
        }

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

        if (file.getName().toLowerCase().endsWith(WepsFileChooser.fileExts[WepsFileChooser.Filetype.CROP.ordinal()])) {
            if (wepsIconCrop.getIconHeight() >= 0 && wepsIconCrop.getIconWidth() >= 0) {
                return wepsIconCrop;
            }
        }

        if (file.isDirectory()) {
            TFile sFile = new TFile(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 {

        @Override
        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
            super.insertString(fb, offset, string, attr);
        }

        @Override
        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 Filetype getType(String pTypeName) {

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

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

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

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

    /**
     *
     * @return
     */
    public boolean getPersitSelectedFile() {
        return persitSelectedFile;
    }

    /**
     *
     * @param persit
     */
    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
     */
    @Override
    public void approveSelection() {
        try {
            TFile dir = new TFile(getSelectedFile().getAbsolutePath());
            TFile 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.\n"
                            + "Please 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 == Filetype.PROJDIR || type == Filetype.DIR
                            || type == Filetype.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 == Filetype.SOILDB) {
                        super.approveSelection();
                    } else if (type == Filetype.MANAGE && runfile.canRead()
                            && (runfile.getName().toLowerCase().endsWith(fileExts[type.ordinal()])
                            || runfile.getName().toLowerCase().endsWith(fileExts[Filetype.XML.ordinal()]))) {
                        super.approveSelection();
                    } else if (type == Filetype.PROJECT
                            && runfile.getName().toLowerCase().endsWith(RunFileData.ProjectSuffix)
                            && dir.getInnerArchive() != null) {
                        JOptionPane.showMessageDialog(this,
                                "Opening projects inside an archive is not allowed.\n"
                                + "Please choose a different project.", "WEPS", JOptionPane.WARNING_MESSAGE);
                        return;
                    } else if (type == Filetype.ERROR) {
                        //new code
                        super.approveSelection();
                    } else if (runfile.canRead() && runfile.getName().toLowerCase().endsWith(fileExts[type.ordinal()])) {
                        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 (HeadlessException e) {
            //System.err.println("WepsFileChooser:approveSelection:"+e);
        }
    }

    private boolean typeIsDirectory(Filetype type) {
        return type == Filetype.PROJDIR || type == Filetype.DIR || type == Filetype.RUNDIR;
    }

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

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

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

    /**
     *
     * @param e
     */
    @Override
    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);
            TFile dir = new TFile(((java.io.File) e.getNewValue()).getAbsolutePath());
            if (dir == null) {
                return;
            }
            if (dir.getName().equals("")) {
                return;
            }
            if (type == Filetype.PROJECT) {
                if (dir.getAbsolutePath().toLowerCase().endsWith(fileExts[Filetype.PROJECT.ordinal()])) {
                    super.approveSelection();
                }
            }
            if (type == Filetype.RUN) {
                if (dir.getAbsolutePath().toLowerCase().endsWith(fileExts[Filetype.RUN.ordinal()])) {
                    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;
        }
    }

    /**
     *
     * @param de
     */
    @Override
    public void changedUpdate(DocumentEvent de) {
        updateOldFileName();
    }

    /**
     *
     * @param de
     */
    @Override
    public void insertUpdate(DocumentEvent de) {
        updateOldFileName();
    }

    /**
     *
     * @param de
     */
    @Override
    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 (Component component : components) {
                Component child = findJTextField(component);
                if (child != null) {
                    return child;
                }
            }
        }
        return null;
    }

    /**
     *
     * @param text
     */
    public void setText(String text) {
        forceEdit = true;
        dialogTextField.setText(text);
    }

    /**
     *
     * @return
     */
    public String getText() {
        return dialogTextField.getText();
    }

    static class WepsFileFilter extends FileFilter {

        WepsFileFilter() {
            type = WepsFileChooser.Filetype.PROJECT;
        }

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

        }
//    private int action;
        private final Filetype type;

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

            // directories are always OK
            if (f.isDirectory()) {
                return true;
            }

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

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

        public Filetype getType() {
            return type;
        }
    }

}//end of class WepsFileChooser
