/**
 * A basic implementation of the JFrame class.
 */
package usda.weru.weps;

import usda.weru.util.tree.WepsTreeComboBox;
import usda.weru.util.tree.WepsTreeNodeFile;
import de.schlichtherle.truezip.file.TFile;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Frame;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.File;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import javax.help.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.tree.TreePath;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; 
import usda.weru.mcrew.MCREWConfig;
import usda.weru.mcrew.ManageData;
import usda.weru.mcrew.MCREWWindow;
import static usda.weru.mcrew.TablePanel.tablePanelNewFilePropChange;
import static usda.weru.mcrew.TablePanel.tablePanelNewFilePropChangeSkip;
import usda.weru.remoteDataAccess.csip.CsipLmodUtil;
import usda.weru.remoteDataAccess.remoteFiles.inetFile.CrLmodFile;
import usda.weru.soil.OrganicSoilException;
import usda.weru.util.tree.WepsTreeModelSoil;
import usda.weru.soil.Soil;
import usda.weru.util.*;
import usda.weru.util.tree.WepsTreeModelMan;
import usda.weru.util.tree.WepsTreeNode;
import usda.weru.util.tree.WepsTreeNodeCrLmod;
import usda.weru.util.tree.WepsTreeNodeRemote;
import usda.weru.util.wepsFileChooser2.WepsFileChooser2;
import usda.weru.util.wepsFileChooser2.WepsFileTypes2;

/**
 * Wrapper for display panel to select and edit management and soil files
 * This GUI class allows a user to select the management files and Soil files
 * from the project or template directories and then launch the respective applications
 * based on the button click events i:e either MCREW or SOIL viewer application.
 * @author  manmohan, wjr=<b>Rotation</b><p>Displays the Management file chosen</p> 
 * @version 1.0
 */
public class AuxPanel extends usda.weru.weps.gui.AuxPanel_n implements PropertyChangeListener {

    private static final long serialVersionUID = 1L;

    private static final Logger LOGGER = LogManager.getLogger(AuxPanel.class);
    private static MCREWWindow mm = null;
    //public boolean MCREWLabelState = true;
    private Soil ss = null;
    public static String calibFactorDialogManFile = "Not Selected Yet";
    public JRootPane temp = null;
    public JPanel temp1 = null;
    public Thread t = null;
    private ConfigData c_cd;
    private WepsTreeModelSoil c_soilModel;
    private WepsTreeModelMan c_manModel;
    private HelpBroker hb = null;

    public boolean mcrewLabelState = true;
    public boolean soilLabelState = true;
    private boolean mcrewLoadingFlg = false;
    private boolean soil_replace = false;
    private boolean mcrewEnabled = true; //isn't being used - EL
    private boolean McrewEditFlg = false; //Added by Neha | isn't be used - EL
    private boolean overflew = false; // used by setManageFile

    private String manDir = ""; //management template directory
    private String soilDir = ""; // soil template directory
    private String soilDB = ""; //Soil database ConfigData
    private String projDir = ""; //projDir
    private String soilFileName = "";
    private String manFileName = "";
    private String mcrewDir = ""; //MCREW ConfigData
    private String mcrewDataConfigFile = "";
    private String manSkel = "";
    private String cropDB = "";
    private String manoperdb = "";
    private String units = ""; // Added by Sada
    private String formatOperationDate = "";
    private String oldManTreePath;
    private String oldSoilTreePath;

    /**
     *
     * Default constructor for AuxPanel Holds parameter information (name and  value) and the methods that are used for
     * data retrieval and manipulation.
     * 
     * Primary 
     */
    public AuxPanel() {
        this (false);
    }
    
    public AuxPanel(ConfigData cd, boolean initMcrew) {
        this(initMcrew);
        c_cd = cd;
    }

    /**
     * Constructor that sets the help broker object for the AuxPanel frame 
     * besides just calling the default constructor to initialize other items
     * and add help to the components sitting in its container.
     * @param hb is the help broker object that links the help items
     * from WEPS help API to the respective components on the panel if and 
     * when triggered. 
     */
    public AuxPanel(HelpBroker hb) {
        this();
        this.hb = hb;
    }

    /**
     * Constructor that sets the title of AuxPanel frame besides calling the
     * default constructor to initialize other items and add help to the 
     * components sitting in its container.
     * @param sTitle is the title heading for the frame that holds the 
     * components and makes it visible in it.
     */
    public AuxPanel(String sTitle) {
        this();
        setTitle(sTitle);
    }
    
    public AuxPanel(boolean enableMcrew) {
        super();
        JP_main.setVisible(true);

        addHelp();
        
        init(enableMcrew);
    }
    
    private final static MouseAdapter mouseAdapter = new MouseAdapter() {
    };
    
    public void runOrganicReplacement() {
        //PropertyChangeEvent organicEvent = new PropertyChangeEvent(this, null, null, ConfigData.getDefault().getDataParsed(ConfigData.SoilOrganicFile));
        //setSoilFile(organicEvent);
        //changes.firePropertyChange(RunFileData.SoilFile, null, ConfigData.getDefault().getDataParsed(ConfigData.SoilOrganicFile));
        //soilActionPerformed(null);
        TFile organicFile = new TFile(ConfigData.getDefault().getDataParsed(ConfigData.SoilOrganicFile));
        WepsTreeNodeFile wtnf = new WepsTreeNodeFile(organicFile);
        loadSelectedSoil(wtnf);
    }
    
    public void setRefreshButtonsVisible(boolean visible) {
       JB_refreshSoil.setVisible(visible);
       JB_refreshMan.setVisible(visible);
       revalidate();
    }
    
    protected void init(boolean enableMcrew) {
        setRefreshButtonsVisible(ConfigData.getIntParm(ConfigData.auxRefresh, 1) == 1);
        mcrewEnabled = enableMcrew;
        c_soilModel = new WepsTreeModelSoil(g_soilTreeCombo, true);
        c_soilModel.configurePropertyChangeListeners();
        g_soilTreeCombo.setModel(c_soilModel);
        g_soilTreeCombo.addPropertyChangeListener(WepsTreeComboBox.PROP_SELECTED_ITEM, (PropertyChangeEvent evt) -> {
            TFile file;
            Object newValue = evt.getNewValue();
            
            try {
                if (evt.getPropertyName().equals(WepsTreeComboBox.PROP_SELECTED_ITEM) && newValue != null) {
                    file = ((WepsTreeNode) newValue).getNodeData();
                    if(soil_replace) {
                        System.out.println("Soil replaced prior to loadSelected");
                        loadSelectedSoil();
                        ss = new Soil(file.getAbsolutePath());
                        ss.refreshPanels();
                        ss.progExit();
                        changes.firePropertyChange(RunFileData.SoilFile, null, ConfigData.SoilOrganicFile);
                        soil_replace = false;
                    }else if (file != null && !soilFileName.contentEquals(file.getAbsolutePath())) {
                        loadSelectedSoil();
                        ss = new Soil(file.getAbsolutePath());
                        ss.refreshPanels();
                        ss.progExit();
                        if(soil_replace) {
                            System.out.println("Soil replaced after loadSelected");
                        }
                        changes.firePropertyChange(RunFileData.SoilFile, null, file.getAbsolutePath());
                    }
//                    ss = new Soil(file.getAbsolutePath());
//                    ss.refreshPanels();
                    ss = new Soil(file.getAbsolutePath());
                    ss.refreshPanels();
                    ss.progExit();
                    
                }
            } catch (IOException ex) {
                System.err.println("AuxPanel.java:init - could not get Soil File data : reverting to previous soil file"); 
                revertSoilFileToPrevious(); // This was added to make sure the soil file goes back if there is problems loading the soil file from db. - EL
            }
        });
        
        c_manModel = new WepsTreeModelMan(g_manTreeCombo, true);
        c_manModel.configureListeners();
        g_manTreeCombo.setModel(c_manModel);
        
        if (enableMcrew) {
            g_manTreeCombo.addPropertyChangeListener(WepsTreeComboBox.PROP_SELECTED_ITEM, manTreeListener);
        } else {
            g_manTreeCombo.setEnabled(false);
            JL_mcrew.setEnabled(false);
        }
    }
    
    public void enableMcrewElements() {

        g_manTreeCombo.setEnabled(true);
        JL_mcrew.setEnabled(true);
        g_manTreeCombo.addPropertyChangeListener(WepsTreeComboBox.PROP_SELECTED_ITEM, manTreeListener);

        // now that propertychange listener is active, 
        // reset the default selection so that the handler (above) will see it.
        try {
            Object selItem = g_manTreeCombo.getSelectedItem();
            if (selItem != null) {
                g_manTreeCombo.setSelectedPath(new TreePath (selItem));
            }
        } catch (java.lang.IllegalArgumentException TreePathMustNotBeNull) {
            /* This error happens too consistently I'm just catching it. Doesn't seem
            to affect anything either, just pops up an error message and continues just fine. */
            System.err.println("java.lang.IllegalArgumentException: path in TreePath must be non null.\n" +
                    "See enableMcrewElements() in AuxPanel.java for more information if needed.");
        }
    }
    
    public void enableManCombo(boolean enable) {
        JL_mcrew.setEnabled(enable);
        g_manTreeCombo.setEnabled(enable);
    }
    
    PropertyChangeListener manTreeListener =  new PropertyChangeListener() { 

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            TFile file = null;
            Object newValue = evt.getNewValue();
            
            try {
                if (newValue instanceof WepsTreeNode) {
                    file = ((WepsTreeNode) newValue).getNodeData();
                    if(!file.exists() || !file.isFile()) {
                        System.out.println("Error: File selection is not valid.");
                        return;        
                    }
                    Weps.setManName(file.getAbsolutePath());
                    String newProjDir = projDir.replaceAll("\\\\", "/");
                    String newFileAbsPath = file.getParentFile().getAbsolutePath().replaceAll("\\\\", "/");
                    if ((newValue instanceof WepsTreeNodeFile || newValue instanceof WepsTreeNodeCrLmod) && !newFileAbsPath.contentEquals(newProjDir)) {
                        File movedFile = new File (projDir, file.getName());
                        try {
                            file.cp(movedFile);
                        } catch(AccessDeniedException e) {
                            JOptionPane.showMessageDialog(null,
                                "ERROR: Duplicate open file in project directory.\nPlease close and remove to continue loading.",
                                "Duplicate File Error",
                                JOptionPane.ERROR_MESSAGE);
                            System.err.println("Couldn't copy file.");
                            return;
                        } catch (java.nio.file.FileSystemException fss) {
                            // There is no good way to handle the dir having the same name,
                            // so were just going to inform the user of the issue and move on.
                            try {
                                movedFile = new File(projDir, Util.purgeExtensions(file.getName(), ".man") + "_NEW.man");
                                file.cp(movedFile);
                                JOptionPane.showMessageDialog(null, "A file or directory with the same name as\n" +
                                        "the managment you selected already exists in the directory.\n" +
                                        "A new file was made with \"_NEW\" appended:\n" + 
                                        movedFile.getAbsolutePath(), "New File in Project Directory", JOptionPane.INFORMATION_MESSAGE);
                            } catch (Exception e) {
                                JOptionPane.showMessageDialog(null,
                                    "ERROR: Could not copy management file into directory. \n" +
                                            "Please close and remove to continue loading.",
                                    "File Copy Error",
                                JOptionPane.ERROR_MESSAGE);
                                return;
                            }
                        }
                        ManageData mdat = new ManageData();
                        mdat.readDataFile(movedFile.getAbsolutePath());
//                        System.out.println("here"+mdat.getVersion());
                        firePropChangeLater(RunFileData.ManageFile, null, movedFile.getAbsolutePath());
//                        System.out.println("heremoved");
                    } else if (!manFileName.contentEquals(file.getAbsolutePath())) {
                        
                        firePropChangeLater(RunFileData.ManageFile, null, file.getAbsolutePath());
//                        System.out.println("herenotmoved");
                    }
                }
            } catch (IOException ignore) {
                //clearManageFile();
            }
        }
    };

    /**
     * This method adds help pages to the different labels, buttons, text field, etc.
     * that are on the auxiliary panel GUI.
     */
    private void addHelp() {
        CSH.setHelpIDString(JP_main, "MCREWSoilPanel_html");
        CSH.setHelpIDString(JL_mcrew, "MCREWBand_html");
        CSH.setHelpIDString(JB_projMan, "MCREWBand_html");
        CSH.setHelpIDString(JB_tempMan, "MCREWBand_html");
        CSH.setHelpIDString(g_manTreeCombo, "MCREWBand_html");
        CSH.setHelpIDString(JL_soil, "SoilBand_html");
        CSH.setHelpIDString(JB_projSoil, "SoilBand_html");
        CSH.setHelpIDString(JB_tempSoil, "SoilBand_html");
        CSH.setHelpIDString(g_soilTreeCombo, "SoilBand_html");
    }

    /**
     * Entry point for testing AuxPanel
     * This method is used if this dialog is rum as an independent application.
     * @param args These are the command line arguments passed to the main method.
     */
    static public void main(String args[]) {
        String projectsDir = "";

        WepsFileChooser2 wfc = new WepsFileChooser2(WepsFileTypes2.Project, projectsDir,
                WepsFileChooser2.Action.Select);
        //set the tooltip of "home" button to "Home" instead of "Desktop"
        wfc.homeToolTip(wfc);
        //remove the NewFolder button
        wfc.disableNewFolder(wfc);

        wfc.setCurrentDirectory("c:/weps/weps.install/projects");

        RunFileData rfd = new RunFileData();

        if (wfc.showDialog(null) == WepsFileChooser2.APPROVE_OPTION) {
            TFile sf = new TFile(wfc.getSelectedFile());
            try {
                projectsDir = sf.getCanonicalPath();
            } catch (java.io.IOException e) {//System.err.println(
                //	"Error getting canoncial path of projectsDir");
            }
            rfd.readRunData(projectsDir);
            //	rfd.showRunFileData("this is a test");
        } else {
            System.exit(1);
        }

        AuxPanel ap = new AuxPanel();
        ap.setVisible(true);
        rfd.addPropertyChangeListener(ap);
        ap.addPropertyChangeListener(rfd);
        rfd.fireAll(ap);
    }

    /**
     * This method triggers specific actions based upon who generates the 
     * events that occur on accessing these components sitting in their parent
     * containers. 
     * @param e The generated event by the component's access.
     */
    @Override
    public void propertyChange(PropertyChangeEvent e) {
        switch (e.getPropertyName()) {
            case RunFileData.SoilFile:                
                // If this change came from the soil viewer,
                // then send it on to RunFiledata.
                // RunFiledata will then issue a change that will
                // come here and get dealt with in the else clause.
                if (e.getSource() instanceof usda.weru.soil.Soil) {
                    changes.firePropertyChange(e);
                } else {
                    setSoilFile(e);
                }
                break;
            case tablePanelNewFilePropChange:
                setManageFile(e);
                break;
            case tablePanelNewFilePropChangeSkip:
                setManageFile(e,true);
                break;
            case RunFileData.ManageFile:
                setManageFile(e);
                break;
            case RunFileData.ManageFileSkip:
                setManageFile(e,true);
                break;
            case ConfigData.ManTemp:
                manDir = ConfigData.getDefault().getDataParsed(ConfigData.ManTemp);
                break;
            case ConfigData.SoilDB:
                soilDB = ConfigData.getDefault().getDataParsed(ConfigData.SoilDB);
                break;
            case ConfigData.ManSkel:
                manSkel = ConfigData.getDefault().getDataParsed(ConfigData.ManSkel);
                break;
            case ConfigData.SystemCropDB:
                cropDB = ConfigData.getDefault().getDataParsed(ConfigData.SystemCropDB);
                break;
            case ConfigData.MCREW:
                mcrewDir = ConfigData.getDefault().getDataParsed(ConfigData.MCREW);
                break;
            case ConfigData.McrewDataConfigFile:
                mcrewDataConfigFile = (String) e.getNewValue();
                break;
            case ConfigData.McrewEdit: //doesn't do anything -EL
                setMcrewEdit(e);
                break;
            case ConfigData.SystemOpDB:
                manoperdb = ConfigData.getDefault().getDataParsed(ConfigData.SystemOpDB);
                break;
            case ConfigData.CurrentProj:
                setCurrentProj(e);
                break;
            case ConfigData.Units:
                //Added by Sada
                units = (String) e.getNewValue();
                break;
            case ConfigData.crlmodEnabled:
//                c_manModel = new WepsTreeModelMan(g_manTreeCombo, true);
//                g_manTreeCombo.setModel(c_manModel);
//                g_manTreeCombo.revalidate();
//                g_manTreeCombo.repaint();
//                this.revalidate();
//                this.repaint();
                break;
            case usda.weru.mcrew.MCREWWindow.FILE_NAME:
//                System.out.println("herefromaux?");
                changes.firePropertyChange(RunFileData.ManageFile, null,
                        (String) e.getNewValue());
                break;
            case usda.weru.mcrew.MCREWWindow.WINDOW_CLOSING:
                TFile mcrewFile = new TFile(mm.getAbsoluteFileName());
                
                //file should exist before we do anything with it
                if (mcrewFile.exists()) {
                    String mcrewFileName = mcrewFile.getName();
                    
                    // strip suffix so that only file Name is displayed and uniformity is maintained.
                    if (mcrewFileName.toUpperCase().endsWith(".MAN")) {
                        mcrewFileName = mcrewFileName.substring(0, mcrewFileName.lastIndexOf('.'));
                    } else if (mcrewFileName.toUpperCase().endsWith(".XML")) {
                        mcrewFileName = mcrewFileName.substring(0, mcrewFileName.lastIndexOf('.'));
                    }

                    //if filename isn't null or empty change aux panel
                    if (mm.getFileName() != null && !mm.getFileName().isEmpty()) {
                        g_manTreeCombo.getComboBox().removeAllItems();
                        g_manTreeCombo.getComboBox().addItem(mcrewFileName + ".man"); // cheeky way to assure .man ext appears on the file
                        oldManTreePath = (String)g_manTreeCombo.getComboBox().getSelectedItem();
                        g_manTreeCombo.getComboBox().setSelectedItem(mcrewFileName);

                        if(oldManTreePath == null) {
                            oldManTreePath = (String)g_manTreeCombo.getComboBox().getSelectedItem();
                        }

                        changes.firePropertyChange(RunFileData.ManageFile, null, mm.getAbsoluteFileName());
                    }
                }
                
                mm = null;
                setMCREWLabelState(true);
                break;
            case ConfigData.FormatOperationDate:
                formatOperationDate = (String) e.getNewValue();
                break;
            case ConfigData.HideProjectFileButtons: {
                String value = e.getNewValue().toString();
                if (value.equals("1")) {
                    JB_projMan.setVisible(false);
                    JB_projSoil.setVisible(false);
                } else {
                    JB_projMan.setVisible(true);
                    JB_projSoil.setVisible(true);
                }
                break;
            }
            case ConfigData.HideTemplatetFileButtons: {
                String value = e.getNewValue().toString();
                if (value.equals("1")) {
                    JB_tempMan.setVisible(false);
                    JB_tempSoil.setVisible(false);
                } else {
                    JB_tempMan.setVisible(true);
                    JB_tempSoil.setVisible(true);
                }
                break;
            }
        }

    }

    /**
     * This method assigns the number of rotation years to the text field 
     * that stores the value to be referred in future
     * @param filnam The name of the file that holds the integer value for the
     * number of rotation years to be assigned to the variable.
     */
    void setRotationYears(String filnam) {
        if (filnam == null || filnam.length() == 0 || filnam.equals("none")) {
            return;
        }
        try {
            ManageData data = new ManageData();
            int years = data.readRotationLength(filnam);
            changes.firePropertyChange(RunFileData.RotationYears, null, Integer.toString(years));
        } catch (Exception e) {
            LOGGER.error("Unable to set rotation years.", e);
        }
    }

    /**
     * Handlers for property changes. This method selects and sets the soil 
     * file passed as an argument.
     * @param e The event occurs when a new soil file is selected which will 
     * be used for pulling the data into the Soil UI screens for analysis purpose.
     */
    private void setSoilFile(PropertyChangeEvent e) {
        String filename = (String) e.getNewValue();
        if (filename == null) {
            //clearSoilFile();
            return;
        }
        
        if(filename.isEmpty() || filename.equals(RunFileData.DefaultSoilFileName)) {
            soilFileName = "";
            clearSoilFile();
        }
        
        soilFileName = filename;
        //refresh the project node so the soil exists.
        WepsTreeNodeFile projectNode = c_soilModel.getProjectNode();
        projectNode.refreshChildren();
        c_soilModel.nodeStructureChanged(projectNode);

        TFile sf = new TFile(filename);
        if (sf.exists()) {
            WepsTreeNodeFile nodeToSelect = projectNode.getDecendantNode(sf);
            if (nodeToSelect != null) {
                TreePath treePath = new TreePath(c_soilModel.getPathToRoot(nodeToSelect));
                g_soilTreeCombo.setSelectedPath(treePath);
            }
        } else {
            //file does not exist so revert
            soilFileName = "";
            if (!filename.equals("")) {
                changes.firePropertyChange(RunFileData.SoilFile, null, "");
            }
            return;
        }

        String mySoilFile = sf.getName();
        int sfindex = mySoilFile.lastIndexOf(".");
        
        if (mySoilFile.contains("null")) {
            
            JOptionPane.showMessageDialog(this, 
                    "There was an error downloading " + mySoilFile + "\n File contains null data.",
                    "Error loading file",
                    JOptionPane.ERROR_MESSAGE);
            try {
                Files.deleteIfExists(Paths.get(sf.getAbsolutePath()));
            } catch (IOException ex) {
                System.out.println("file no exist");
            }
            this.revertSoilFileToPrevious();
            return;
        }
        
        if (sfindex > 0) {
            String sFileStr = mySoilFile;
            g_soilTreeCombo.getComboBox().removeAllItems();
            g_soilTreeCombo.getComboBox().addItem(sFileStr);
            oldSoilTreePath = (String) g_soilTreeCombo.getComboBox().getSelectedItem();
            g_soilTreeCombo.getComboBox().setSelectedItem(sFileStr);

        }   
    }

    public void clearManageFile() {
        g_manTreeCombo.setSelectedPath(null);
        g_manTreeCombo.getComboBox().addItem("(Select a management file)");
        g_manTreeCombo.getComboBox().setSelectedItem("(Select a management file)");
    }
    /** useful for reverting the GUI when we happen across an unusable man file
     */
    private void revertManFileToPrevious(){
        if(oldManTreePath != null){
//            System.out.println("hereoldman" + oldManTreePath);
            
            g_manTreeCombo.getComboBox().removeAllItems();
            g_manTreeCombo.getComboBox().addItem(oldManTreePath);
//            g_manTreeCombo.sets
//            manFileName =projDir+File.separator+oldManTreePath;
//            setManageFile(manFileName);
//            WepsTreeNodeFile wtnf = new WepsTreeNodeFile(new TFile(manFileName));
//            g_manTreeCombo.getComboBox().setSelectedItem(wtnf);
            g_manTreeCombo.getComboBox().setSelectedItem(oldManTreePath);
            g_manTreeCombo.getComboBox().updateUI();
            
//            System.out.println("heremanpath " + g_manTreeCombo.getTree().getAnchorSelectionPath().toString());
//            setManageFile(g_manTreeCombo.getTree().getSelectionPath().getPath().toString());
//            g_manTreeCombo.setSelectedItem(oldManTreePath);
//            g_manTreeCombo.fromComboBox = true;
//            changes.firePropertyChange(RunFileData.ManageFile, null, manFileName);
//            System.out.println("heres sel item" + g_manTreeCombo.getComboBox().getSelectedItem().toString());
//            g_manTreeCombo.setSelectedPath();
//            g_manTreeCombo.getComboBox().updateUI();
        }else{
            clearManageFile();
        }
    }
    
    private void revertSoilFileToPrevious() {
        if (oldSoilTreePath != null) {
           g_soilTreeCombo.getComboBox().removeAllItems();
           g_soilTreeCombo.getComboBox().addItem(oldSoilTreePath);
           g_soilTreeCombo.getComboBox().setSelectedItem(oldSoilTreePath);
           g_soilTreeCombo.getComboBox().updateUI();
        } else {
            soilFileName = "";
            clearSoilFile();
        }
    }
    
    private void clearSoilFile() {
        g_soilTreeCombo.setSelectedPath(null);
        g_soilTreeCombo.getComboBox().removeAllItems();
        g_soilTreeCombo.getComboBox().addItem("(Select a soil file)");
        g_soilTreeCombo.getComboBox().setSelectedItem("(Select a soil file)");
        g_soilTreeCombo.updateUI();
    }

    /**
     * Handlers for property changes. This method selects and sets the management 
     * file passed as an argument to be pulled into the MCREW application to
     * analyze, modify, study and interpret the data.
     * @param e The event occurs when a new management(.MAN) file is selected which will 
     * be used for pulling the data into the MCREW UI screens.
     */
    private void setManageFile(PropertyChangeEvent e) {
//        System.out.println("heresettingman");
// need to have a check for the project folder here.
        tempskip = false;
//        System.out.println("nothere");
        if(((String) e.getNewValue()).startsWith(Weps.getInstance().getAuxPanel().projDir)){
//            System.out.println("here");
            tempskip = false;
        }
        setManageFile((String) e.getNewValue());
        
    }
    private boolean tempskip = false;
    private void setManageFile(PropertyChangeEvent e, boolean skip){
        tempskip = skip;
        setManageFile((String) e.getNewValue());
    }
    public void setManageFile(String manFile, boolean skip) {
    tempskip = skip;
    setManageFile(manFile);
    }
    
    
    public void setManageFile(String manFile) {
        ManageData md = new ManageData();
        int res = 0;
        if(tempskip){
            md.readDataFile(manFile, true);
        }else{
            res = md.readDataFile(manFile); 
        }
        
//        System.out.println("heremfvers" + md.getVersion());
        if (manFileName.contentEquals(manFile) || res ==-4) {
            revertManFileToPrevious();
            firePropChangeLater(RunFileData.ManageFile, "", manFileName);
            refreshMan();
//            setManageFile(Weps.getManName(), true);
            return;
        }
        
        //String oldManFileName = manFileName;
        //TreePath oldTreePath = g_manTreeCombo.getTree().getSelectionPath();
        //System.out.println("manFile: " + manFile);
        if(manFile == null || manFile.length() == 0) {
            System.out.println("No file selected.");
            return;
        }
        
        try {
            if (manFile.equals(RunFileData.DefaultManageFileName)) {
                manFileName = "";
                clearManageFile();
            } else if (!(new TFile(manFile).exists())) {
                manFileName = "";
                clearManageFile();
            } else {
                //refresh the project node so the soil exists.
                WepsTreeNodeFile projectNode = c_manModel.getProjectNode();
                if (projectNode != null) {
                    projectNode.refreshChildren();
                }
                
                c_manModel.nodeStructureChanged(projectNode);

                TFile mf = new TFile(manFile);
                if (mf.exists() && mf.length() <= 0 && mf.isFile()) {
                    JOptionPane.showMessageDialog(null, "The Management File \n " + manFile + " exists,\n but contains NO data.",
                            "Problem with Management File", JOptionPane.ERROR_MESSAGE);
                    clearManageFile();
                    return;
                }

                ManageData manData = new ManageData();
                // Needs to be "true" here if MCREW directly loads file, but needs to be "false" if selected from the dropdown choice list
                // Need to determine how to do this correctly - LEW
                
                if (manData.getUpdateStatus()) {
                    try {
                        // If file updated, then it was copied to project dir.
                        // Stop loading it, and fire a change to the new updated filename.
                        String fromFile = mf.getCanonicalPath();
                        String toFile = new TFile(projDir, mf.getName()).getCanonicalPath();
                        // fire it later, because Weps is still going to receive this same current prop change
                        // So let Weps receive this current one first, "later" receive the new name.
                        firePropChangeLater(RunFileData.ManageFile, fromFile, toFile);
                        return;
                    } catch (java.io.IOException ioe) {
                        LOGGER.error("Unable to copy management file.", ioe);
                    }
                }
                
                // MEH set now to prevent re-entry above.
                manFileName = mf.getAbsolutePath();
                int result = manData.readDataFile(mf.getAbsolutePath(), false);
//                System.out.println("herereadvers"+ manData.getVersion());
                if (result == ManageData.K_SUCCESS_UPDATED) {
                    mf = new TFile(manData.manFile);
                } else if(result == ManageData.K_CANCELED_UPDATE){
                    
                    revertManFileToPrevious();
                    firePropertyChange(RunFileData.ManageFile, "", manFileName);
                } else if (result == ManageData.K_FAILURE_OLD) {
                    WepsMessageLog log = new WepsMessageLog();
                    log.logMessage(WepsMessage.MessageSeverity.ERROR, "There were errors with the previously saved Management file: " + oldManTreePath);
                    WepsMessageDialog.showMessageList(null, "Management File Errors",
                            "Errors were detected with the management file.\n" + manFile, projDir, log.getMessages());                    
                    revertManFileToPrevious();
                    return;
                } else if (result == ManageData.K_WRONG_VERSION) {
                    WepsMessageLog log = new WepsMessageLog();
                    log.logMessage(WepsMessage.MessageSeverity.ERROR, "The file appears to be corrupted - Wrong mgt file version.");
                    WepsMessageDialog.showMessageList(null, "Management File Errors",
                            "Errors were detected with the management file.\n" + manFile, projDir, log.getMessages());
                    revertManFileToPrevious();
                    firePropChangeLater(RunFileData.ManageFile, "", manFileName);
                    return;
                } else if (result == ManageData.K_CORRUPTED_FILE) {
                    WepsMessageLog log = new WepsMessageLog();
                    log.logMessage(WepsMessage.MessageSeverity.ERROR, "The file appears to be corrupted.");
                    WepsMessageDialog.showMessageList(null, "Management File Errors",
                            "Errors were detected with the management file.\n" + manFile, projDir, log.getMessages());
                    revertManFileToPrevious();
                    firePropChangeLater(RunFileData.ManageFile, "", manFileName);
                    return;
                }

                ArrayList<String> msgs = new ArrayList<>();
                

                int checkResult = manData.checkAllConditions(msgs);
                
                //-ihaas-
                if (!msgs.isEmpty()){
                    // msgs.remove(0); //Remove the first msg so that it can be more specific below
                }
                if (checkResult == ManageData.CHECK_FAILED) {
                    if(g_manTreeCombo.fromComboBox){
//                    checkResult = ManageData.CHECK_WARNING;
//                        System.out.println("here is where update failed from combobox");
                    g_manTreeCombo.fromComboBox = false;
                    }else{
                    WepsMessageLog log = new WepsMessageLog();
                    log.logMessage(WepsMessage.MessageSeverity.ERROR, 
                            "The following operations are missing necessary parameters");
                    for (String msg : msgs) {
                        log.logMessage(WepsMessage.MessageSeverity.ERROR, msg);
                    }
                    WepsMessageDialog.showMessageList(null, "Management File Errors",
                            "Errors were detected with the management file.\n" + manFile, projDir, log.getMessages());
                    revertManFileToPrevious();
                    firePropChangeLater(RunFileData.ManageFile, "", manFileName);
                    return;}
                } else if (checkResult == ManageData.CHECK_WARNING) {
                    WepsMessageLog log = new WepsMessageLog();
                    String mes = "The following operations have extra parameters."+
                            "\nThey will not affect WEPS in any way and they will not be saved in any new files.\n";
                    log.logMessage(WepsMessage.MessageSeverity.WARNING, mes);
                    for (String msg : msgs) {
                        log.logMessage(WepsMessage.MessageSeverity.WARNING, msg);
                    }
                    WepsMessageDialog.showMessageList(null, "Management File Warnings",
                            "Warnings were detected with the management file.\n" + manFile, projDir, log.getMessages());
                    //firePropChangeLater(RunFileData.ManageFile, "", manFileName);
                    //return;
                    manFileName = mf.getAbsolutePath();
                    Weps.setManName(manFileName); //-ihaas-
                    firePropChangeLater(RunFileData.ManageFile, null, manFileName);                    
                } else {
                    manFileName = mf.getAbsolutePath();
                    Weps.setManName(manFileName); //-ihaas-
                    firePropChangeLater(RunFileData.ManageFile, null, manFileName);
                }

                setRotationYears(manFileName);
                if (!mf.exists() || mf.isDirectory()) {
                    manFile = "";

                    if (!overflew) {
                        changes.firePropertyChange(RunFileData.ManageFile, null, "");
                    }
                    overflew = false;
                    clearManageFile();
                    return;
                }

                String myMgmtFile = mf.getName();
                int mfindex = myMgmtFile.lastIndexOf(".");
                if (mfindex > 0) {
                    String mFileStr = myMgmtFile.substring(0, mfindex);
                    //JTF_manFileName.setText(mFileStr);
                    g_manTreeCombo.getComboBox().removeAllItems();
                    g_manTreeCombo.getComboBox().addItem(mFileStr + ".man"); //cheeky way to make sure man files appear with .man (because if they are from cache they won't have .man)
                    
                    oldManTreePath = (String)g_manTreeCombo.getComboBox().getSelectedItem(); 
                    
                    g_manTreeCombo.getComboBox().setSelectedItem(mFileStr);
                    calibFactorDialogManFile = mFileStr;

                    WepsTreeNodeFile nodeToSelect = projectNode.getDecendantNode(mf);
                    
                    if (nodeToSelect != null) {
                        oldManTreePath = (String)g_manTreeCombo.getComboBox().getSelectedItem();
                        g_manTreeCombo.setSelectedPath(new TreePath(c_soilModel.getPathToRoot(nodeToSelect)));
                    }
                } else {
                    if (manFile.equals(RunFileData.DefaultManageFileName)) {
                        manFileName = "";
                        clearManageFile();
                    } else {
                        //System.err.println("Management File with extension not Found " + myMgmtFile );
                    }
                }
            } 
        } catch (StackOverflowError sofe) {
            overflew = true;
        }
        // Need to update the runfile data or runs will use wrong management file.
        changes.firePropertyChange(RunFileData.ManageFile, null, manFileName);
    }  
                
    /**
     * Handlers for property changes. This method sets flag for the MCREW to 
     * screen & data rows as editable.
     * 
     * doesn't do anything - EL
     * 
     * @param e The event occurs when the flag is changed from editable to 
     * non-editable or vice versa.
     */
    private void setMcrewEdit(PropertyChangeEvent e) {
        McrewEditFlg = ((String) e.getNewValue()).equals("1");

    }

    /**
     * Handlers for property changes. This method selects the project currently 
     * being worked on as the current project for various screens and reports
     * to refer to it when asked for it. 
     * @param e The event occurs when the value is to be set for what will be
     * the current project path.
     */
    private void setCurrentProj(PropertyChangeEvent e) {
        projDir = Util.parse(e.getNewValue().toString());
    }

    /**
     * Open management file in project directory
     * 
     * @param event
     */
    @Override
    public void JBProjMan_actionPerformed(java.awt.event.ActionEvent event) {
        if (JB_projMan.isEnabled()) {
            String proj_setting = ConfigData.getDefault().getDataParsed(ConfigData.MGT_P_BUTTON_DEFAULT);
            if (proj_setting == null) proj_setting = projDir;
            if (proj_setting.equals("")) proj_setting = projDir;
            // -ihaas- Check upgm config param for allowed versions.
            boolean usingUpgm = ConfigData.checkParmValue("CD-upgm-manx", "1");
            WepsFileTypes2[] types;
            if (usingUpgm) {
                types = new WepsFileTypes2[] {WepsFileTypes2.Management, WepsFileTypes2.MANX};
            }
            else {
                types = new WepsFileTypes2[] {WepsFileTypes2.Management};
            }
            
            WepsFileChooser2 wfc = new WepsFileChooser2(types, proj_setting, WepsFileChooser2.Action.Select);
            
            wfc.setCurrentDirectory(projDir);
            
            
            //set the tooltip of "home" button to "Home" instead of "Desktop"
            wfc.homeToolTip(wfc);
            //remove the NewFolder button
            wfc.disableNewFolder(wfc);
            //System.out.println("allowing buttons");
            wfc.enableFolderButtons();
            wfc.setDialogTitle("Select Management File");
            wfc.enableDbButton(false);
            
            
            if (wfc.showDialog(this.JP_main) == WepsFileChooser2.APPROVE_OPTION) {
                if(wfc.getSelectedFile().getAbsolutePath().toUpperCase().endsWith(".MAN") || wfc.getSelectedFile().getAbsolutePath().toUpperCase().endsWith(".MANX")) {
                    setManageFile(wfc.getSelectedFile().getAbsolutePath());
                }            
           }
        }
    }

    /**
     * Open management file in template directory
     * @param event The mouse click or keyboard event generated when the template
     * management button is clicked to open the file chooser for selecting
     * the template .MAN file.
     */
    @Override
    public void JBTempMan_actionPerformed(java.awt.event.ActionEvent event) {
        boolean usingUpgm = ConfigData.checkParmValue("CD-upgm-manx", "1");
        WepsFileTypes2[] types;
        if (usingUpgm) {
            types = new WepsFileTypes2[] {WepsFileTypes2.Management, WepsFileTypes2.MANX};
        }
        else {
            types = new WepsFileTypes2[] {WepsFileTypes2.Management};
        }
        if (JB_tempMan.isEnabled()) {
            if(ConfigData.checkParmValue(ConfigData.crlmodEnabled, "1")) {
                String CRLMOD_config = ConfigData.getDefault().getDataParsed(ConfigData.MGT_T_BUTTON_DEFAULT);

                WepsFileChooser2 wfc;
                boolean crlmod = CRLMOD_config == null ? true : false;
                CrLmodFile rootFile = null;
                if (!crlmod) if (CRLMOD_config.equals("CRLMOD Managements") || CRLMOD_config.equals("CrLmod Managements") ||
                        CRLMOD_config.equals("") || crlmod) {
                    crlmod = true;
                }
                // check that file actually exists
                if (!crlmod) {
                    if (!(new TFile(CRLMOD_config)).exists()) {
                        // if file doesn't exist, then use default crlmod
                        crlmod = true;
                    }
                }
                if (crlmod) {
                    System.out.println("Setting default template location to CRLMOD database.");
                    rootFile = new CrLmodFile("CRLMOD Managements", CsipLmodUtil.lmodType.lmodManagement);
                    rootFile.listFiles();
                    wfc = new WepsFileChooser2(types, rootFile, WepsFileChooser2.Action.Select);
                    wfc.setCurrentDirectory_remote_file(rootFile);
                    crlmod = true;
                } else {
                    System.out.println("Setting custom location from configuration files for CRLMOD Templates.");
                    wfc = new WepsFileChooser2(types, CRLMOD_config, WepsFileChooser2.Action.Select);
                    wfc.setCurrentDirectory(CRLMOD_config);
                }
                wfc.enableDbButton(false);
                wfc.setFileFilter(WepsFileTypes2.Management.getFileFilter());
                
                TFile shaMan = new TFile(Util.parse(Weps.getInstance().cd.getData(ConfigData.SharedManDB)));
                TFile locMan = new TFile(Util.parse(Weps.getInstance().cd.getData(ConfigData.LocalManDB)));
                TFile sysMan = new TFile(Util.parse(MCREWConfig.getDirectoryName(ConfigData.ManTemp)));
                wfc.getPath().addItem(shaMan);
                wfc.getPath().addItem(locMan);
                wfc.getPath().addItem(sysMan);
                if (crlmod) {
                    wfc.getPath().addAndSelectItem(rootFile);
                    wfc.setDefaultDirectory(rootFile);
                } else {
                    wfc.setDefaultDirectory(new TFile(CRLMOD_config));
                }
                
                //set the tooltip of "home" button to "Home" instead of "Desktop"
                wfc.homeToolTip(wfc);
                //remove the NewFolder button
                wfc.disableNewFolder(wfc);
                wfc.enableFolderButtons();
                
                if (wfc.showDialog(this.JP_main) == WepsFileChooser2.APPROVE_OPTION) {
                    setManageFile(wfc.getSelectedFile().getAbsolutePath());
                }
            } else {
                System.out.println("Setting default template location to system database.");
                String location = Util.parse(Weps.getInstance().cd.getData(ConfigData.ManTemp));
                WepsFileChooser2 wfc = new WepsFileChooser2(types, location, WepsFileChooser2.Action.Select);
                wfc.setCurrentDirectory(location);
                TFile shaMan = new TFile(Util.parse(Weps.getInstance().cd.getDataParsed(ConfigData.SharedManDB)));
                TFile locMan = new TFile(Util.parse(Weps.getInstance().cd.getDataParsed(ConfigData.LocalManDB)));
                wfc.getPath().addItem(locMan);
                wfc.getPath().addItem(shaMan);
                //set the tooltip of "home" button to "Home" instead of "Desktop"
                wfc.homeToolTip(wfc);
                //remove the NewFolder button
                wfc.disableNewFolder(wfc);
                wfc.enableFolderButtons();
                if (!(wfc.showDialog(this.JP_main) == WepsFileChooser2.APPROVE_OPTION)) {
                        setManageFile(wfc.getSelectedFile().getAbsolutePath());
                }
            }
        }
    }

    /**
     * Open soil file in project directory
     * @param event The mouse click or keyboard event generated when the project
     * soil button is clicked to open the file chooser for selecting
     * the project SOIL file.
     */
    @Override
    public void JBProjSoil_actionPerformed(java.awt.event.ActionEvent event) {
        if (JB_projSoil.isEnabled()) {
            WepsFileChooser2 wfc = new WepsFileChooser2(WepsFileTypes2.Soil, projDir,
                    WepsFileChooser2.Action.Select);
            wfc.setCurrentDirectory(projDir);
            //set the tooltip of "home" button to "Home" instead of "Desktop"
            wfc.homeToolTip(wfc);
            //remove the NewFolder button
            wfc.disableNewFolder(wfc);

            if (wfc.showDialog(this.JP_main) == WepsFileChooser2.APPROVE_OPTION) {
                try {
                    //JTF_soilFileName.setText(wfc.getSelectedFile().getName());
                    String sFileStr = wfc.getSelectedFile().getName();
                    g_soilTreeCombo.getComboBox().removeAllItems();
                    g_soilTreeCombo.getComboBox().addItem(sFileStr);
                    oldSoilTreePath = (String) g_soilTreeCombo.getComboBox().getSelectedItem();
                    g_soilTreeCombo.getComboBox().setSelectedItem(sFileStr);
                    changes.firePropertyChange(RunFileData.SoilFile, null, wfc.getSelectedFile().getCanonicalPath());
//                    changes.firePropertyChange(RunFileData.SoilRockFragments, null, "0.0");
//                    changes.firePropertyChange(RunFileData.AverageSlope, null, "-1");
                } catch (IOException e) {
                    //System.err.println("Error getting canoncial path of soil file");
                }
            }
        }
    }

    /**
     * Open soil file in template directory
     * @param event The mouse click or keyboard event generated when the template
     * soil button is clicked to open the file chooser for selecting
     * the template SOIL file.
     */
    @Override
    public void JBTempSoil_actionPerformed(java.awt.event.ActionEvent event) {

        if (JB_tempSoil.isEnabled()) {
            WepsFileChooser2 wfc = new WepsFileChooser2(WepsFileTypes2.Soil, soilDB,
                    WepsFileChooser2.Action.Select);
            wfc.setCurrentDirectory(soilDB);
            //set the tooltip of "home" button to "Home" instead of "Desktop"
            wfc.homeToolTip(wfc);
            //remove the NewFolder button
            wfc.disableNewFolder(wfc);

            if (wfc.showDialog(this.JP_main) == WepsFileChooser2.APPROVE_OPTION) {
                try {
                    changes.firePropertyChange(RunFileData.SoilFile, null, wfc.getSelectedFile().getCanonicalPath());
                } catch (IOException e) {
                    LOGGER.error("Could not get file path.", e);
                }
            }

        }

    }//end of JBTempSoil_actionPerformed

    public void JBShow_actionPerformed(java.awt.event.ActionEvent event) {
        changes.firePropertyChange(RunFileData.ShowRunData, null, "AuxPanel");

    }
    
    /**
     * Used to notify listeners of changes
     */
    private PropertyChangeSupport changes = new PropertyChangeSupport(this);

    /**
     * Adds listeners to the components to recognize the changes made on this panel.
     * @param l The listener object for the components on the panel to be removed.
     */
    @Override
    public void addPropertyChangeListener(PropertyChangeListener l) {
        changes.addPropertyChangeListener(l);
    }

    /**
     * Removes listeners for the components to recognize the changes made on this panel.
     * @param l The listener object for the components on the panel to be removed.
     */
    @Override
    public void removePropertyChangeListener(PropertyChangeListener l) {
        changes.removePropertyChangeListener(l);
    }

    @Override
    public void soilActionPerformed(java.awt.event.ActionEvent evt) {
        
        if (soilFileName.length() <= 0) {
            JOptionPane.showMessageDialog(null, "No soil file has been selected.\n"+
                                                "Please select a soil file,\n"+
                                                "then enter the Soil editor.",
                    "No Soil File Selected", JOptionPane.ERROR_MESSAGE);
            return;
        }

        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        ////System.out.println("AP_JLS_mC: " + soilFileName);
        if (soilLabelState) {
            if (ss != null && ss.isValid()) {//React to change button clicks.

                ss.setState(JFrame.NORMAL);
                // ss.setVisible(true);
                setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                return;
            } else {
                //Lock the soil buttons.
                setSoilLabelState(false);
                TFile sfn = new TFile(soilFileName);
                //System.out.println("AuxPanel : JLSoil_mouseClicked : SoilFilename on Line 388 : " + soilFileName);
                if (sfn.exists()) {
                    TFile pd = new TFile(projDir);
                    try {
                        if (!sfn.getParentFile().getCanonicalPath().equals(pd.getCanonicalPath())) {
                            //				//System.out.println("AP_JLS_mC: not in dir " + soilFileName + " " + projDir);
                            String fromFile = sfn.getCanonicalPath();
                            String toFile = new TFile(pd, sfn.getName()).getCanonicalPath();
                            //System.out.println("AuxPanel : JLSoil_mouseClicked : toFile : " + toFile );
                            //System.out.println("AuxPanel : JLSoil_mouseClicked : toFile : " + fromFile );
                            if(!Util.copyFile(fromFile, toFile)) {
                                setSoilLabelState(true);
                                if (ss != null) {
                                    ss.removePropertyChangeListener(AuxPanel.this);
                                    ss = null;
                                }
                                return;
                            }
                            changes.firePropertyChange(RunFileData.SoilFile, null, toFile);
//                            changes.firePropertyChange(RunFileData.SoilRockFragments, null, "0.0");
//                            changes.firePropertyChange(RunFileData.AverageSlope, null, "-1");
                        } else {
                            //					//System.out.println("AP_JLS_mC: in dir " + soilFileName + " " + projDir);
                        }
                    } catch (java.io.IOException e) {
                        //System.err.println("AP_JLS_mC: IO error on " + soilFileName + " or " + projDir);
                        //System.err.println("AP_JLS_mC: " + e);
                    }
                } else {
                    //System.out.println("AP_JLS_mC: " + "calling Soil  with no Soil file");
                }

                ss = new Soil(soilFileName, projDir, soilDir);

                if (ConfigData.getDefault().isSoilReadonly()) {
                    ss.setReadonly(true);
                } else {
                    ss.setReadonly(false);
                }

                ss.addWindowListener(new WindowAdapter() {

                    @Override
                    public void windowClosed(WindowEvent e) {
                        setSoilLabelState(true);
                        if (ss != null) {
                            ss.removePropertyChangeListener(AuxPanel.this);
                            ss = null;
                        }

                    }

                });

                //}
                ss.addPropertyChangeListener(this);
                c_cd.fireAll(ss);
                ss.setVisible(true);
                setSoilLabelState(false);
            }
        } else {
            int windowState = ss.getExtendedState();
            if ((windowState & ICONIFIED) == ICONIFIED) {
                ss.setExtendedState(windowState - ICONIFIED);
            }
            ss.toFront();
            ss.requestFocusInWindow();
        }
        ss.toFront();        // new usda.weru.soil.Soil(soilFileName, soilDir).setVisible(true);
        // Modified above code to open soil from specific project Directory
        setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    }

    /**
     * Disables the Soil button on the panel if a SoilUI object is already instantiated
     * else makes it enabled it. 
     * @param flag The boolean value that determines whether the label should be 
     * set enabled or not.
     */
    public void setSoilLabelState(boolean flag) {
        JL_soil.setEnabled(flag);
        soilLabelState = flag;
        JB_projSoil.setEnabled(flag);
        JB_tempSoil.setEnabled(flag);
        g_soilTreeCombo.setEnabled(flag);
    }

    /**
     * Disables the MCREW button on the panel if a MCREW object is already instantiated
     * else makes it enabled it. 
     * @param flag The boolean value that determines whether the label should be 
     * set enabled or not.
     */
    public void setMCREWLabelState(boolean flag) {
        JL_mcrew.setEnabled(flag);
        mcrewLabelState = flag;
        JB_projMan.setEnabled(flag);
        JB_tempMan.setEnabled(flag);
        g_manTreeCombo.setEnabled(flag);

    }
     /**
     * check if file is read only,
     * if it is, pop up an alert to tell the user that they opened a read only file and disable save options based on
     * if they continue with it
     */
    public boolean readOnlyFile(String path){
        //only check files from our project directory, made sure '/'s were consistent in the path strings
        if(path.replace("/", "\\").contains(projDir.replace("/", "\\"))){
            if(Util.isReadOnly(path)){
                JOptionPane.showMessageDialog(this, "Read Only File Detected \nPlease Provide MCREW With a Writable File","Read Only File Detected", JOptionPane.ERROR_MESSAGE);
                setMCREWLabelState(true);
                mm.closeMcrew();
                return true;
            }
        }
        return false;
    }
    
//     /**
//     * This function checks if a file is read only.
//     */
//    public boolean isReadOnly(String path) {
//        File file = new File(path);
//        if(!file.isFile()){
//            //if it does not exist, return false
//            return false;
//        }
//        return !file.canWrite();   
//    }
    

    /**
     * Brings the MCREW UI screen up using the data from the management file
     * shown or selected.
     * @param evt
     */
    @Override
    public void mcrewActionPerformed(java.awt.event.ActionEvent evt) {

        if (mcrewLabelState) {
            //if double click on the left mouse button, then ignore.
            //By Neha-If McrewLoadingFlg is TRUE, means Multiple mouse clicks on Mcrew button before it can load
            if (mm != null && mm.isValid()) {
                if (mcrewLoadingFlg != true) {
                    mm.setState(Frame.NORMAL);
                }
            } else if (mcrewLoadingFlg != true) {
                // This checks that a copy of this man file exists in the
                // project directory, and if not copies it over. Then
                // sets manFileName to the project directory copy for MCREW editing -CKM
                checkManFile_forProjectDirectory();

                File manFileCheck = new File(manFileName);
                if (!manFileCheck.isFile() && ConfigData.getDefault().isEnabledEmptyManagementFilePopupMessage()) {
                    JOptionPane.showMessageDialog(null, "No management file has been selected.\n"
                            + "Please select a management file,\n"
                            + "then enter the MCREW editor.",
                            "No Management File Selected", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                //Lock the buttons
                setMCREWLabelState(false);

                // By Neha-Change the Cursor to Wait Cursor, set the McrewLoadingFlg ON
                mcrewLoadingFlg = true;
                Component prev1 = null;
                Component prev2 = null;

                Component c = this.JP_main;
                do {
                    prev2 = prev1;
                    prev1 = c;
                    c = c.getParent();
                    if (c == null) {
                        temp = (JRootPane) prev2;
                        temp.getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                        temp.getGlassPane().setVisible(true);
                        temp.addMouseListener(mouseAdapter);                   
                    }
                } while (c != null);

                AuxPanel thisPanel = this;
                Thread th = new Thread("MCREW Action") {

                    @Override
                    public void run() {

                        try {
                            //The ConfigData is now linked to Mcrew in Weps.main(); --Joseph
                            String title = Application.MCREW.getName() + "(" + Application.MCREW.getDescription() + ")";

                            //checkManFile_forProjectDirectory(); // Too late to be useful? moved up
                            String[] inputFiles = {AuxPanel.this.manFileName};

                            if (!ConfigData.isSingleFileMode()) {
                                ArrayList<String> toInput = new ArrayList<>();
                                TFile proj = new TFile(ConfigData.getDefault().getData(ConfigData.CurrentProj));
                                for (TFile child : proj.listFiles()) {
                                    if (child.getName().endsWith(".man")) {
                                        toInput.add(child.getAbsolutePath());
                                    }
                                }
                                inputFiles = new String[toInput.size()];
                                inputFiles = toInput.toArray(inputFiles);
                            }
                            try {
                                mm = new MCREWWindow(title, projDir, inputFiles, c_cd);
                                mm.setWaiting(true);
                                mm.addPropertyChangeListenerToTablePanel(tablePanelNewFilePropChange, thisPanel);
                            } catch (NullPointerException e) {
                                System.out.println("MCREW Failed to load. Resetting for another attempt.");
                                Weps.getInstance().enableMcrewElements();
                                setMCREWLabelState(true);
                                temp.getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                                return;
                            }

                            /**
                             * By Neha- Disabling or Enabling the Open, and Open
                             * Copy of Template Menu option as MCREW is being
                             * opened from Weps here[not stand-alone]. This
                             * option is set in the "Miscellaneous" tab of
                             * Config Panel of Weps.
                             */

                            if (mm.getLabelState() == false) {
                                setMCREWLabelState(false);
                            } else {
                                setMCREWLabelState(true);
                            }
                            try {
                                //remove the mouse listener and add the Property Change Listener for mm - Mcrew
                                removeAndAddListener();
                                mm.toFront();
                                //Mcrew Loading has finished.Turn off the flag
                                mcrewLoadingFlg = false;
                                //now exit if it is read only
                                readOnlyFile(inputFiles[0]);
                            } catch (IllegalStateException ise) {
                                mcrewLoadingFlg = false;
                                setMCREWLabelState(true);
                                mm = null;

                                interrupt();
                            }
                        } finally {
                            if (mm != null) {
                                boolean result = mm.setWaiting(false);
                                if (!result) {
                                    System.out.println("MCREW Failed to load. Resetting for another attempt.");
                                    Weps.getInstance().enableMcrewElements();
                                    temp.getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                                    setMCREWLabelState(true);
                                    mcrewLoadingFlg = false;
                                    mm = null;
                                    interrupt();

                                }

                            }
                            temp.getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                        }

                    }
                };

                //set the lowest priority to this thread, so that the main thread can listen 
                //to mouse events and change the  cursor to Wait cursor
                SwingUtilities.invokeLater(th);
            } else {
                throw new RuntimeException("Unhandled state MCrew state " + (mm == null ? "mm=null"
                        : "mm NOT null, mm.isValid=" + mm.isValid() + " mm.isOpen=" + MCREWWindow.isOpen()));
            }
        } else {
            if (mm != null) {
                int windowState = mm.getExtendedState();
                if ((windowState & ICONIFIED) == ICONIFIED) {
                    mm.setExtendedState(windowState - ICONIFIED);
                }
                mm.toFront();
                mm.requestFocusInWindow();
            }
        }
    }
    

    /**
     * This method makes sure that the current man file exists in the project directory
     * Sets manFileName to project-dir copy instead of run-dir copy CKM
     */
    private void checkManFile_forProjectDirectory() {
        // Check for file in project directory
        String manFileName_NOPATH = manFileName.substring(manFileName.lastIndexOf(File.separator) + 1);

        // Create path to file in project dir
        manFileName_NOPATH = projDir + File.separator + manFileName_NOPATH;

        try {
            // try to open man file in project directory
            File testProjectHasMan = new File(manFileName_NOPATH);

            if (testProjectHasMan != null) {
 
                if (!testProjectHasMan.exists()) {
                    // Need to copy then , doesnt exist in project dir
                    System.out.println("No man file found in project directory, copying over...");
                    // copy
                    //Files.copy(new File(manFileName), new File (manFileName_NOPATH));
                    new TFile(manFileName).cp(new File (manFileName_NOPATH));

                    // check exits
                    if (new File(manFileName_NOPATH).exists()) {
                        System.out.println("Copy success!");
                        // set to project directory
                        manFileName = manFileName_NOPATH;
                    }
                } else {
                    // man file exists in project directory, make sure man file name is set to that
                    manFileName = manFileName_NOPATH;
                }
            }
        } catch (Exception e) {
            // nothing, just dont want to break the whole method on this
            //System.out.println("exception...");
        }
    }

    @Override
    public void refreshMan() {
        c_manModel.refresh();
    }
    
    @Override
    public void refreshSoil() {
        c_soilModel.refresh();
    }
    
    /**
     * This method removes listener from the root pane and adds it to the MCREW
     * object as a property change listener to get the feedback on events occurig
     * on MCREW GUI object.
     */
    public void removeAndAddListener() {
        temp.getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        temp.getGlassPane().setVisible(false);
        temp.removeMouseListener(mouseAdapter);
        mm.addPropertyChangeListener(this);
        //System.out.println("The object is"+this.getClass().getName());
    }

    /**
     * This method sets the cursor to a pre-defined shape on entering the set 
     * bounds. 
     * @param event Tells when the mouse entered a pre-defined bounds to trigger 
     * this event.
     */
    public void mouseEntered(MouseEvent event) {
        //System.out.println("AuxPanel:Mouse entered event occured");
        //System.out.println("Mouse position: x="+event.getX()+" y= "+event.getY());
        temp.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

    }
    
// EL - not used anywhere
//    public HashMap<String, String> getMcrewConfig() {
//        HashMap<String, String> config = new HashMap<>();
//        config.put(ConfigData.ManTemp, manDir);
//        config.put(ConfigData.ManSkel, manSkel);
//        config.put(ConfigData.SystemCropDB, cropDB);
//        config.put(ConfigData.MCREW, mcrewDir);
//        config.put(ConfigData.McrewDataConfigFile, mcrewDataConfigFile);
//        config.put(ConfigData.SystemOpDB, manoperdb);
//        config.put(ConfigData.Units, units);
//        config.put(ConfigData.FormatOperationDate, formatOperationDate);
//        return config;
//    }

    private void loadSelectedSoil() {
        Object o = g_soilTreeCombo.getSelectedItem();
        if (o instanceof WepsTreeNode) {
            if (o instanceof WepsTreeNodeFile) {
                try {
                    TFile file = ((WepsTreeNode) o).getNodeData();
                    if (!file.getParentFile().getAbsolutePath().contentEquals(projDir)) {
                        File movedFile = new File (projDir, file.getName());
                        file.cp(movedFile);
                        firePropChangeLater(RunFileData.SoilFile, null, movedFile.getAbsolutePath());
                    }

//                    ss = new Soil(g_soilTreeCombo.getName());
//                    TFile file2 = ((WepsTreeNode) o).getNodeData();
//                    
//                    ss = new Soil(file2.getAbsolutePath());
//                    ss.refreshPanels();
//                    ss.progExit();
                    
                } catch (IOException e) {
                }
            } else if (o instanceof WepsTreeNodeRemote) {
                SwingWorker<TFile, Void> task = new SwingWorker<TFile, Void> () {
                    @Override
                    protected TFile doInBackground() throws Exception {
                        try {
                            System.out.println("Are we trying the soil?");
                            return ((WepsTreeNode)o).getNodeData();
                        } catch(OrganicSoilException ose) {
                            //System.out.println("Organic Soil Exception?");
                            if(ose.getMessage().equals("Revert")) {
                                return null;
                            }
                            else if(ose.getMessage().equals("Default")) {
                                soil_replace = true;
                                //System.out.println("replacing soil");
                                //Default to the organic soil file specified in the config panel.
                                changes.firePropertyChange(RunFileData.SoilFile, null,
                                                ConfigData.getDefault().getDataParsed(ConfigData.SoilOrganicFile));
                                return new TFile(ConfigData.getDefault().getDataParsed(ConfigData.SoilOrganicFile));
                            }
                            throw new Exception(ose);
                        }
                    }

                    @Override
                   protected void done() {
                       try {
                            TFile nodeFile = get();

                            if (nodeFile == null) {
                                //Revert to previous soil file.
                                g_soilTreeCombo.setSelectedPath(null);
                                g_soilTreeCombo.getComboBox().removeAllItems();
                                String name = new TFile(soilFileName).getName();
                                g_soilTreeCombo.getComboBox().addItem(name);
                                oldSoilTreePath = (String) g_soilTreeCombo.getComboBox().getSelectedItem();
                                g_soilTreeCombo.getComboBox().setSelectedItem(name);
                                nodeFile = new TFile(soilFileName);
                            }

                            final TFile fileParm = nodeFile;
                            // Fire propertychange again. (This is the propertychange that got here).
                            // This time, we are setting the selection to the local downloaded file FROM Csip
                            // instead of leaving it set to the Csip reference.
                            // (It works to skip this 2nd call, but is more immediately clear to the user to do it).
                            firePropChangeLater(RunFileData.SoilFile, soilFileName, fileParm.getAbsolutePath());
//                            SwingUtilities.invokeLater(new Runnable() {
//                                @Override
//                                public void run() {
//                                    changes.firePropertyChange(RunFileData.SoilFile, soilFileName, fileParm.getAbsolutePath());
//                                }
//                            });
                       } catch (Exception ex) {
                            clearSoilFile();
                       } finally {
                       }
                   }
                } ;
                task.run();
            }
        }
    }

    private void loadSelectedSoil(Object obj) {
        g_soilTreeCombo.setSelectedItem(obj);
        this.loadSelectedSoil();
    }
    
    void firePropChangeLater (String property, Object oldVal, Object newVal) {
        SwingUtilities.invokeLater(() -> {
            changes.firePropertyChange(property, oldVal, newVal);
        });
    }
}
