package usda.weru.soil;

import de.schlichtherle.truezip.file.TFile;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import java.beans.*;
import java.io.FileNotFoundException;
import javax.help.*;
import java.lang.ClassLoader.*;
import usda.weru.util.*;

/**
 * main() is in this function
 */
final public class Soil extends usda.weru.soil.gui.SoilUI_n implements PropertyChangeListener {

    private static final long serialVersionUID = 1L;

    static {
        openSoilWindows = new Vector<Soil>();
    }
    static Vector<Soil> openSoilWindows;

    /**
     *
     * @return
     */
    public static boolean isOpen() {
        return Soil.openSoilWindows.size() > 0;
    }

    /**
     *
     */
    public static final String WindowClosing = "Soil-WindowClosing";
    IFC ifcptr;    //variables for help system

    /**
     *
     */
    public HelpBroker hb_soil;
    private String projectsPath = "";
    String inputSoilName;
    String viewitem;
    String dbName = "";
    String prjName = "";
    private final String soiluiid = "WEPS Soil User Interface";
    private boolean selFlg;
    private boolean c_readonly = false;
    private boolean c_estimate = false;
    Grid GridID = null;
    Grid GridSurfProp = null;
    Grid GridLayrProp = null;

    /**
     *
     * @param fileName
     */
    public Soil(String fileName) {
        this(fileName, "", "");
    }

    /**
     *
     * @param fileName
     * @param prjName
     * @param dbName
     */
    public Soil(String fileName, String prjName, String dbName) {
        super();
        if (Soil.openSoilWindows.contains(this) == false) {
            Soil.openSoilWindows.add(this);
        }
        this.prjName = prjName;
        this.dbName = dbName;
        this.changes = new PropertyChangeSupport(this);

        inputSoilName = fileName;

        setResizable(true);

        setLocation(50, 50);

        Dimension d = getSize();
        d.height -= 60;
        d.width -= 10;
        setTitle(soiluiid + "Initial Field Conditions " + inputSoilName);
        //Setting the Icon Image in the title bar
        super.setIconImage(About.getWeruIconImage());

        ifcptr = new IFC();
        try {
            ifcptr.readIfc(inputSoilName);
            setMenuEnable("Save", true);
            setMenuEnable("Save As", true);
            setMenuEnable("Print", true);
        } catch (FileNotFoundException e) {
        }

        addPopupMenu();
        viewLayers();
        repaint();
        validate();
        Util.loadToolTips((Container) this, new TFile("cfg", "soiltooltips.cfg"));
        addHelp();  //make addHelp active by JG
    }

    /**
     *
     * @param b
     */
    @Override
    public void setVisible(boolean b) {
        if (inputSoilName == null || inputSoilName.trim().length() == 0) {
            newFile();
        }
        super.setVisible(b);
    }

    private void commitEdits() {
        GridID.commitEdit(true);
        GridLayrProp.commitEdit(true);
        GridSurfProp.commitEdit(true);
    }

    /**
     *
     */
    public void updateEstimateButtons() {
        boolean estimate = c_estimate && selFlg && !c_readonly;

        JB_estimate.setEnabled(estimate);
        estimateItem.setEnabled(estimate);
    }

    /**
     *
     * @param readonly
     */
    public void setReadonly(boolean readonly) {
        if (readonly) {
            Soil.openSoilWindows.remove(this);
        } else {
            if (Soil.openSoilWindows.contains(this) == false) {
                Soil.openSoilWindows.add(this);
            }
        }
        c_readonly = readonly;
        //Buttons
        JB_open.setEnabled(!readonly);
        JB_open.setVisible(!readonly);
        JB_save.setEnabled(!readonly);
        JB_save.setVisible(!readonly);
        JB_copy.setEnabled(!readonly);
        JB_copy.setVisible(!readonly);
        JB_cut.setEnabled(!readonly);
        JB_cut.setVisible(!readonly);
        JB_paste.setEnabled(!readonly);
        JB_paste.setVisible(!readonly);
        openItem.setEnabled(!readonly);
        openItem.setVisible(!readonly);
        JB_estimate.setVisible(!readonly);

        //Menus
        M_edit.setEnabled(!readonly);
        M_edit.setVisible(!readonly);

        //Menu Items
        newItem.setEnabled(!readonly);
        newItem.setVisible(!readonly);
        saveAsItem.setEnabled(!readonly);
        saveAsItem.setVisible(!readonly);
        saveAsTemplateItem.setEnabled(!readonly);
        saveAsTemplateItem.setVisible(!readonly);
        saveItem.setVisible(!readonly);
        saveItem.setVisible(!readonly);
        openRemoteDB.setEnabled(!readonly);
        openRemoteDB.setVisible(!readonly);

        //Pass to tables
        if (GridID != null) {
            GridID.setReadonly(readonly);
        }
        if (GridLayrProp != null) {
            GridLayrProp.setReadonly(readonly);
        }
        if (GridSurfProp != null) {
            GridSurfProp.setReadonly(readonly);
        }

    }

    /**
     *
     * @return
     */
    public boolean getReadonly() {
        return c_readonly;
    }

    protected void newFile() {
        inputSoilName = "";
        setMenuEnable("Save", false);
        setMenuEnable("Save As", true);
        setMenuEnable("print", true);
        setTitle(soiluiid + "Initial Field Conditions New File");
        ifcptr = new IFC(1);
        viewLayers();
        if (JB_estimate.isVisible()) {
            selFlg = true;
            updateEstimateButtons();
            if (GridLayrProp != null) {
                GridID.displayColumns("select");
                GridSurfProp.displayColumns("select");
                GridLayrProp.displayColumns("select");
            }
            all.setState(!selFlg);
            select.setState(selFlg);
        }
    }

    protected void openFile() {

        WepsFileChooser wfc = new WepsFileChooser(WepsFileChooser.Filetype.SOIL,
                projectsPath,
                WepsFileChooser.OPEN);
        wfc.disableNewFolder(wfc);
        wfc.setCurrentDirectory(new de.schlichtherle.truezip.file.TFile((new TFile(projectsPath)).getAbsolutePath()));
        if (wfc.showDialog(this) == JFileChooser.APPROVE_OPTION) {
            inputSoilName = wfc.getSelectedFile().getAbsolutePath();
            setMenuEnable("Save", true);
            setMenuEnable("Save As", true);
            setMenuEnable("print", true);
            setTitle(soiluiid + "Initial Field Conditions " + inputSoilName);
            ifcptr = new IFC();
            try {
                ifcptr.readIfc(inputSoilName);
                viewLayers();
            } catch (java.io.FileNotFoundException e) {
                //System.err.println("S_oF: " + e);
            }
        }
    }

    public void progExit() {
        Soil.openSoilWindows.remove(this);
        if (changes != null) {
            changes.firePropertyChange(WindowClosing, null, "true");
        }
        dispose();
        Util.debugPrint("exit called");
    }

    public void saveIfc() {
        if (inputSoilName == null || inputSoilName.trim().isEmpty()) {
            saveAsIfc();
            return;
        }
        commitEdits();
        Util.debugPrint(true, "<< " + inputSoilName);
        String dir = "";
        String outputSoilNm = "";
        if (ifcptr != null && inputSoilName != null) {
            int index = inputSoilName.lastIndexOf('\\');
            if (index > 0) {
                dir = inputSoilName.substring(0, index);
                outputSoilNm = inputSoilName.substring(index);
            }
            Util.debugPrint("SoilUI : saveIfc : Dir name is : " + dir);
            Util.debugPrint("SoilUI : saveIfc : Soil Name ONLY is : " + outputSoilNm);
            Util.debugPrint("SoilUI : saveIfc : Soil Name is : " + inputSoilName);
            ifcptr.writeNewIfc(new TFile(dir, outputSoilNm).getAbsolutePath(), changes);
        }
    }

    public void saveAsIfc() {
        commitEdits();
        WepsFileChooser wfc = new WepsFileChooser(WepsFileChooser.Filetype.SOIL, prjName, WepsFileChooser.SAVE);

        wfc.setCurrentDirectory(new de.schlichtherle.truezip.file.TFile(prjName));
        TFile soilFile;
        if (inputSoilName == null || inputSoilName.trim().isEmpty()) {
            soilFile = Util.incrementFileName(new TFile(prjName, "new_soil.ifc"));
        } else {
            soilFile = Util.incrementFileName(new TFile(inputSoilName));
        }

        wfc.setPersitSelectedFile(true);
        wfc.setSelectedFile(soilFile);
        wfc.setText(soilFile.getName());
        if (wfc.showDialog(this) == JFileChooser.APPROVE_OPTION) {
            inputSoilName = wfc.getSelectedFile().getAbsolutePath();
            if (ifcptr != null && inputSoilName != null) {
                ifcptr.writeNewIfc(inputSoilName, changes);
                setTitle(soiluiid + "  " + inputSoilName);
            } else {
            }
        }
    }

    /**
     *
     */
    public void saveAsIfcTemplate() {
        commitEdits();
        WepsFileChooser wfc = new WepsFileChooser(WepsFileChooser.Filetype.SOIL, prjName, WepsFileChooser.SAVE);

        String soilDbPath = ConfigData.getDefault().getDataParsed(ConfigData.SoilDB);

        wfc.setCurrentDirectory(new de.schlichtherle.truezip.file.TFile(soilDbPath));
        TFile soilFile;

        if (inputSoilName == null || inputSoilName.trim().isEmpty()) {
            soilFile = Util.incrementFileName(new TFile(soilDbPath, "new_soil.ifc"));
        } else {
            soilFile = Util.incrementFileName(new TFile(soilDbPath, new TFile(inputSoilName).getName()));
        }

        wfc.setPersitSelectedFile(true);
        wfc.setSelectedFile(soilFile);
        wfc.setText(soilFile.getName());
        if (wfc.showDialog(this) == JFileChooser.APPROVE_OPTION) {
            inputSoilName = wfc.getSelectedFile().getAbsolutePath();
            if (ifcptr != null && inputSoilName != null) {
                ifcptr.writeNewIfc(inputSoilName, changes);
                setTitle(soiluiid + "  " + inputSoilName);
            }
        }
    }

    void getSQL() {
        if (dbName.length() == 0) {
            dbName = JOptionPane.showInputDialog(this, "Enter database name (" + this.dbName + ")");
            if (dbName.length() == 0) {
                Util.debugPrint("SUI_gSQL: return null");
                return;
            }
        }
        SoilChooser sc = new SoilChooser(this, new TFile(prjName), new TFile(dbName), changes);
        sc.setVisible(true);
    }
    // following are cut and paste fix to make soil mart data work
    String workingDirectory = "sweep";
    String soilDB = "db/soil";
    static private String cfgFile = "cfg/sweep.cfg";
    SoilChooser c_soilChooser = null;

    /**
     *
     * @param evt
     */
    @Override
    protected void openRemoteDBActionPerformed(java.awt.event.ActionEvent evt) {
        if (c_soilChooser == null) {
            System.out.println("soilDB " + (new TFile(soilDB)).getAbsolutePath());
            System.out.println("working " + (new TFile(workingDirectory)).getAbsolutePath());
            c_soilChooser = new SoilChooser(this, new TFile(workingDirectory), new TFile(soilDB), changes);
        }
        c_soilChooser.setSize(new java.awt.Dimension(500, 500));
        c_soilChooser.setVisible(true);
    }

    protected void editDelete() {
        if (GridLayrProp.showPopup()) {
            GridLayrProp.deleteRow();
            //	pack();
            validate();
            repaint();
        } else {
            JOptionPane.showMessageDialog(this,
                    "Invalid selection", "Error editing layers", JOptionPane.ERROR_MESSAGE);
        }
    }

    protected void editBeforeInsert() {
        if (GridLayrProp.showPopup()) {
            GridLayrProp.insertRowBefore();
            //	pack();
            validate();
            repaint();
        } else {
            JOptionPane.showMessageDialog(this,
                    "Invalid selection", "Error editing layers", JOptionPane.ERROR_MESSAGE);
        }
    }

    protected void editAfterInsert() {
        if (GridLayrProp.showPopup(true)) {
            GridLayrProp.insertRowAfter();
            //	pack();
            validate();
            repaint();
        } else {
            JOptionPane.showMessageDialog(this,
                    "Invalid selection", "Error editing layers", JOptionPane.ERROR_MESSAGE);
        }
    }

    protected void editCut() {
        if (GridLayrProp.showPopup()) {
            GridLayrProp.cutRow();
            //	pack();
            validate();
            repaint();
        } else {
            JOptionPane.showMessageDialog(this,
                    "Invalid selection", "Error editing layers", JOptionPane.ERROR_MESSAGE);
        }
    }

    protected void editCopy() {
        if (GridLayrProp.showPopup()) {
            GridLayrProp.copyRow();
        } else {
            JOptionPane.showMessageDialog(this,
                    "Invalid selection", "Error editing layers", JOptionPane.ERROR_MESSAGE);
        }
    }

    protected void editBeforePaste() {
        if (GridLayrProp.showPopup()) {
            GridLayrProp.pasteBeforeRow();
            validate();
            repaint();
        } else {
            JOptionPane.showMessageDialog(this,
                    "Invalid selection", "Error editing layers", JOptionPane.ERROR_MESSAGE);
        }
    }

    protected void editAfterPaste() {
        if (GridLayrProp.showPopup(true)) {
            GridLayrProp.pasteAfterRow();
            validate();
            repaint();
        } else {
            JOptionPane.showMessageDialog(this,
                    "Invalid selection", "Error editing layers", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * @param evt
     /* These methods deal with the help in soil screen - Neha */
    @Override
    public void HelpJMI_actionPerformed(java.awt.event.ActionEvent evt) {
        //implementing via addHelp
    }

    /**
     *
     * @param evt
     */
    @Override
    public void AboutJMI_actionPerformed(java.awt.event.ActionEvent evt) {
        AboutDialog JAboutDialog1 = new AboutDialog(this, usda.weru.util.Application.SOILUI);
        JAboutDialog1.setModal(true);
        JAboutDialog1.setVisible(true);
    }

    /**
     *
     */
    protected void addHelp() {
        //Skip loading the helpset if we already have it in memory
        if (Help.hasHelpSet("SOIL") == false) {
            loadHelp();
        }

        addCSH(Help.getHelpSet());
    }

    private void loadHelp() {
        String dirFilePath = "help/soil1/soil.hs";
        String soilJarPath = "jar/SoilHelp.jar";
        String jarFilePath = "jar/MasterHelp.jar";

        if (Help.loadJar(jarFilePath, "soil1/soil.hs")) {
            return;
        } else if (Help.loadJar(soilJarPath)) {
            return;
        } else if (Help.loadDirectory(dirFilePath)) {
            return;
        }
    }

    private void addCSH(HelpSet hs_soil) {
        hb_soil = hs_soil.createHelpBroker();
        hb_soil.enableHelpKey(getRootPane(), "SoilIntro_html", hs_soil);
        hb_soil.enableHelpOnButton(helpJMI, "SoilIntro_html", hs_soil);
        hb_soil.enableHelpOnButton(JB_help, "SoilIntro_html", hs_soil);
        ActionListener helper = new CSH.DisplayHelpFromSource(hb_soil);
        //System.out.println("I am in the SOIL addHelp()" + helper);
        helpJMI.addActionListener(helper);

        //contextsensitive help
        JB_CSH.addActionListener(new CSH.DisplayHelpAfterTracking(hs_soil, "javax.help.SecondaryWindow", null));
        CSH.setHelpIDString(MB_main, "soilMenuBar_html");
        CSH.setHelpIDString(M_file, "soilMenuFile_html");
        CSH.setHelpIDString(M_edit, "soilMenuEdit_html");
        CSH.setHelpIDString(M_view, "soilMenuView_html");
        CSH.setHelpIDString(M_help, "soilMenuHelp_html");
        CSH.setHelpIDString(toolbar, "soilButtonBar_html");
        CSH.setHelpIDString(JTB_main, "soilButtonBar_html");
        CSH.setHelpIDString(JB_open, "SoilbuttonOpen_html");
        CSH.setHelpIDString(JB_save, "SoilbuttonSave_html");
        CSH.setHelpIDString(JB_cut, "SoilbuttonCut_html");
        CSH.setHelpIDString(JB_copy, "SoilbuttonCopy_html");
        CSH.setHelpIDString(JB_paste, "SoilbuttonPaste_html");
        CSH.setHelpIDString(JB_print, "SoilbuttonPrint_html");
        CSH.setHelpIDString(JB_estimate, "SoilbuttonEST_html");
        CSH.setHelpIDString(JB_help, "SoilbuttonHelp_html");
        CSH.setHelpIDString(JB_close, "SoilbuttonClose_html");
        CSH.setHelpIDString(JP_soilIdentity, "soilIdentification_html");
        CSH.setHelpIDString(JP_soilSurfaceProp, "soilSurface_html");
        CSH.setHelpIDString(JP_soilLayerProp, "soilLayer_html");
        CSH.setHelpIDString(JSP_text, "soilTextArea_html");
        CSH.setHelpIDString(JTA_warningText, "soilTextArea_html");

    }

    /**
     *
     * @param filnam
     */
    public void viewLayers(String filnam) {
        inputSoilName = filnam;
        viewLayers();
    }

    public void viewLayers() {
        if (ifcptr == null) {
            return;
        }
        if (ifcptr.nsl == 0) {
            return;
        }
        setTitle(soiluiid + "  " + inputSoilName);

        //		tables.removeAll();
        JP_soilIdentity.removeAll();
        GridID = new Grid(ifcptr, 1);
        //tables.add(GridID, BorderLayout.NORTH);
        JP_soilIdentity.add(GridID, BorderLayout.CENTER);

        JP_soilSurfaceProp.removeAll();
        GridSurfProp = new Grid(ifcptr, 2);
        //tables.add(GridSurfProp, BorderLayout.NORTH);
        JP_soilSurfaceProp.add(GridSurfProp, BorderLayout.CENTER);

        JP_soilLayerProp.removeAll();
        GridLayrProp = new Grid(ifcptr, 3);
        //tables.add(GridLayrProp, BorderLayout.NORTH);
        JP_soilLayerProp.add(GridLayrProp, BorderLayout.CENTER);
        JP_soilLayerProp.addMouseListener(popupListener);
        GridLayrProp.addMouseListener(popupListener);

//		JTA_warningText.removeAll();
        JTA_warningText.setText(ifcptr.errorsInIfcFile);
//		JSP_text.getVerticalScrollBar().setValue(0);
//		JTA_warningText.insert("", 0);
//		JViewport jvt = JSP_text.getViewport();
//		jvt.setViewPosition(new java.awt.Point(0,0));
        ifcptr.setGrids(GridID, GridSurfProp, GridLayrProp, JTA_warningText);

        getContentPane().invalidate();
        getContentPane().validate();
        getContentPane().repaint();

        JSP_text.getVerticalScrollBar().setValue(0);
        setReadonly(c_readonly);
    }

    /**
     * @param args***************************************************************************/
    public static void main(String[] args) {
        System.setProperty("line.separator", "\n");	// make file line separator unix compatible
        String x = "";
        String mainConfig = "cfg/weps.cfg";
        String userConfig = null;
        //if the user config is not set use the name of the main config file
        if (userConfig == null) {
            userConfig = About.getUserWeps().getAbsolutePath() + "/" + new TFile(mainConfig).getName();
        }
        ConfigData.getDefault().load(new TFile(mainConfig), new TFile(userConfig));

        new Soil(x).setVisible(true);
    }

    /*****************************************************************************/
    @Override
    public void addNotify() {
        // Record the size of the window prior to calling parents addNotify.
        super.addNotify();
    }
    /*****************************************************************************/
    int initflg = 0;

    /**
     * wj
     public void setVisible(boolean b) {
     }
     r a
     */
    protected void printIfc() {
        PrintJob pj = getToolkit().getPrintJob(this,
                "Print IFC file", new Properties());
        if (pj == null) {
            return;
        }
        ifcptr.printIfc(pj);
        pj.end();
    }

    /********************************************************** wjr*/
    void setMenuEnable(String nam, boolean enabled) {
        JMenuBar mb = this.MB_main;
        for (int idx = 0; idx < mb.getMenuCount(); idx++) {
            JMenu menu = mb.getMenu(idx);
            for (int jdx = 0; jdx < menu.getItemCount(); jdx++) {
                JMenuItem mi = menu.getItem(jdx);
                try {
                    if (nam.equalsIgnoreCase(mi.getActionCommand())) {
                        mi.setEnabled(enabled);
                        return;
                    }
                } catch (java.lang.NullPointerException e) {
                }
            }
        }
    }

    /********************************************************** wj
     * @param e*/
    @Override
    public void propertyChange(PropertyChangeEvent e) {
////System.out.println("S_pC: propName: " + e.getPropertyName() + " -> " + (String) e.getNewValue());
        if (e.getPropertyName().equals(ConfigData.SoilDB)) {
            //dbName = new String((String) e.getNewValue());
        } else if (e.getPropertyName().equals(ConfigData.CurrentProj)) {
            prjName = Util.parse(e.getNewValue().toString());
//Util.debugPrint(true, "prjName: " + prjName);
        } else if (e.getPropertyName().equals(ConfigData.ProjDir)) {
            projectsPath = (String) e.getNewValue();
            projectsPath = new TFile(projectsPath).getAbsolutePath();
//Util.debugPrint(true, "projPath: " + projectsPath);
        } else if (e.getPropertyName().equals(ConfigData.SoilEstimate)) {
            if (e.getNewValue().toString().equals("1")) {
                c_estimate = true;

            } else {
                c_estimate = false;
            }
            updateEstimateButtons();
        } else if (e.getPropertyName().equals(ConfigData.SoilDB)) {
            soilDB = (String) e.getNewValue();
        } else if (e.getPropertyName().equals(ConfigData.SWEEPWorkDir)) {
            workingDirectory = (String) e.getNewValue();
        }
    }
    private PropertyChangeSupport changes = new PropertyChangeSupport(this);

    /**
     * Adds listener to changes made on this panel
     *
     * @param l
     */
    @Override
    public void addPropertyChangeListener(PropertyChangeListener l) {
        changes.addPropertyChangeListener(l);
    }

    /**
     * Removes listener to changes made on this panel
     *
     * @param l
     */
    @Override
    public void removePropertyChangeListener(PropertyChangeListener l) {
        changes.removePropertyChangeListener(l);
    }

    /*********************
     ********************* screen handlers
     *********************/
    @Override
    protected void JBClose_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBClose_ActionPerformed
        progExit();
    }//GEN-LAST:event_JBClose_ActionPerformed

    /**
     *
     * @param evt
     */
    protected void SoilUI_componentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_SoilUI_componentResized
    }//GEN-LAST:event_SoilUI_componentResized

    /**
     *
     * @param evt
     */
    @Override
    protected void MI_new_ActionPerformed(java.awt.event.ActionEvent evt) {
        newFile();
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void MI_open_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MI_open_ActionPerformed
        openFile();
    }//GEN-LAST:event_MI_open_ActionPerformed

    /**
     *
     * @param evt
     */
    @Override
    protected void MI_save_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MI_save_ActionPerformed
        saveIfc();
    }//GEN-LAST:event_MI_save_ActionPerformed

    /**
     *
     * @param evt
     */
    @Override
    protected void MI_saveAs_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MI_saveAs_ActionPerformed
        saveAsIfc();
    }//GEN-LAST:event_MI_saveAs_ActionPerformed

    /**
     *
     * @param evt
     */
    @Override
    protected void saveAsTemplateItem_actionPerformed(ActionEvent evt) {
        saveAsIfcTemplate();
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void MI_print_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MI_print_ActionPerformed
        printIfc();
    }//GEN-LAST:event_MI_print_ActionPerformed

    /**
     *
     * @param evt
     */
    protected void MI_getSQL_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MI_getSQL_ActionPerformed
        getSQL();
    }//GEN-LAST:event_MI_getSQL_ActionPerformed

    /**
     *
     * @param evt
     */
    protected void MI_batch_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MI_batch_ActionPerformed

    }//GEN-LAST:event_MI_batch_ActionPerformed

    /**
     *
     * @param evt
     */
    @Override
    protected void MI_exit_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MI_exit_ActionPerformed
        progExit();
    }//GEN-LAST:event_MI_exit_ActionPerformed

    /**
     *
     * @param evt
     */
    @Override
    protected void MI_cut_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MI_cut_ActionPerformed
        editCut();
    }//GEN-LAST:event_MI_cut_ActionPerformed

    /**
     *
     * @param evt
     */
    @Override
    protected void MI_copy_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MI_copy_ActionPerformed
        editCopy();
    }//GEN-LAST:event_MI_copy_ActionPerformed

    /**
     *
     * @param evt
     */
    @Override
    public void pasteBeforeJMI_actionPerformed(java.awt.event.ActionEvent evt) {
        editBeforePaste();
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void MI_pasteAfter_ActionPerformed(java.awt.event.ActionEvent evt) {
        editAfterPaste();
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void insertBeforeItem_actionPerformed(java.awt.event.ActionEvent evt) {
        editBeforeInsert();
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void insertAfterItem_actionPerformed(java.awt.event.ActionEvent evt) {
        editAfterInsert();
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void deleteItem_actionPerformed(java.awt.event.ActionEvent evt) {
        editDelete();
    }

    /**
     *
     * @param evt
     */
    protected void MI_help_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MI_help_ActionPerformed

    }//GEN-LAST:event_MI_help_ActionPerformed

    /**
     *
     * @param evt
     */
    @Override
    protected void JB_open_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_open_ActionPerformed
        openFile();
    }//GEN-LAST:event_JB_open_ActionPerformed

    /**
     *
     * @param evt
     */
    @Override
    protected void JB_save_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_save_ActionPerformed
        saveIfc();
    }//GEN-LAST:event_JB_save_ActionPerformed

    /**
     *
     * @param evt
     */
    @Override
    protected void JB_cut_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_cut_ActionPerformed
        editCut();
    }//GEN-LAST:event_JB_cut_ActionPerformed

    /**
     *
     * @param evt
     */
    @Override
    protected void JB_copy_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_copy_ActionPerformed
        editCopy();
    }//GEN-LAST:event_JB_copy_ActionPerformed

    /**
     *
     * @param evt
     */
    @Override
    protected void JB_paste_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_paste_ActionPerformed
        //This is called when the tool button Paste is clicked.
        editBeforePaste();
    }//GEN-LAST:event_JB_paste_ActionPerformed

    /**
     *
     * @param evt
     */
    @Override
    protected void JB_print_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_print_ActionPerformed
        printIfc();
    }//GEN-LAST:event_JB_print_ActionPerformed

    /**
     * Exit the Application
     * @param evt
     */
    @Override
    protected void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
        progExit();
    }//GEN-LAST:event_exitForm

    /**
     *
     * @param evt
     */
    @Override
    protected void selectItemStateChanged(java.awt.event.ItemEvent evt) {
        if (evt.getStateChange() != java.awt.event.ItemEvent.SELECTED) {
            return;
        }
        selFlg = true;
        updateEstimateButtons();
        if (GridLayrProp != null) {
            GridID.displayColumns("select");
            GridSurfProp.displayColumns("select");
            GridLayrProp.displayColumns("select");
        }
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void allItemStateChanged(java.awt.event.ItemEvent evt) {
        if (evt.getStateChange() != java.awt.event.ItemEvent.SELECTED) {
            return;
        }
        selFlg = false;
        updateEstimateButtons();
        if (GridLayrProp != null) {

            viewLayers();
            GridID.displayColumns("all");
            GridSurfProp.displayColumns("all");
            GridLayrProp.displayColumns("all");
        }
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void JB_estimateActionPerformed(java.awt.event.ActionEvent evt) {
        commitEdits();
        try {
            ifcptr.estimateFactors();
        } catch (IllegalStateException ise) {
            return;
        }
        selFlg = false;
        updateEstimateButtons();
        all.setState(!selFlg);
        select.setState(selFlg);
        if (GridLayrProp != null) {
            viewLayers();
            GridID.displayColumns("all");
            GridSurfProp.displayColumns("all");
            GridLayrProp.displayColumns("all");
        }
    }
    private JPopupMenu popup, headerPopup;
    private Vector<MenuElement> popupVec;
    private MouseListener popupListener;

    private void addPopupMenu() {
        MenuElement[] menuElements;

        popup = new JPopupMenu();

        popupVec = new Vector<>();

        JMenuItem jmi = new javax.swing.JMenuItem();
        // Now follws multiple row operations
        jmi.setText("Cut Row");
        jmi.setActionCommand("Cut ");
        jmi.addActionListener(new java.awt.event.ActionListener() {

            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editCut();
            }
        });
        popup.add(jmi);

        jmi = new javax.swing.JMenuItem();
        jmi.setText("Copy Row");
        jmi.setActionCommand("Copy");
        jmi.addActionListener(new java.awt.event.ActionListener() {

            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editCopy();
            }
        });
        popup.add(jmi);

        jmi = new javax.swing.JMenuItem();
        jmi.setText("Paste Before Row");
        jmi.setActionCommand("Paste Before Row");
        jmi.addActionListener(new java.awt.event.ActionListener() {

            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editBeforePaste();
            }
        });
        popup.add(jmi);

        jmi = new javax.swing.JMenuItem();
        jmi.setText("Paste After Row");
        jmi.setActionCommand("Paste After Row");
        jmi.addActionListener(new java.awt.event.ActionListener() {

            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editAfterPaste();
            }
        });
        popup.add(jmi);

        jmi = new javax.swing.JMenuItem();
        jmi.setText("Insert Before Row");
        jmi.setActionCommand("Insert Before Row");
        jmi.addActionListener(new java.awt.event.ActionListener() {

            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editBeforeInsert();
            }
        });
        popup.add(jmi);

        jmi = new javax.swing.JMenuItem();
        jmi.setText("Insert After Row");
        jmi.setActionCommand("Insert After Row");
        jmi.addActionListener(new java.awt.event.ActionListener() {

            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editAfterInsert();
            }
        });
        popup.add(jmi);

        jmi = new javax.swing.JMenuItem();
        jmi.setText("Delete Row");
        jmi.setActionCommand("Delete Row");
        jmi.addActionListener(new java.awt.event.ActionListener() {

            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editDelete();
            }
        });
        popup.add(jmi);

        //header popup
        headerPopup = new JPopupMenu();

        jmi = new javax.swing.JMenuItem();
        jmi.setText("Paste");
        jmi.setActionCommand("Paste");
        jmi.addActionListener(new java.awt.event.ActionListener() {

            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editAfterPaste();
            }
        });
        headerPopup.add(jmi);

        jmi = new javax.swing.JMenuItem();
        jmi.setText("Insert");
        jmi.setActionCommand("Insert");
        jmi.addActionListener(new java.awt.event.ActionListener() {

            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editAfterInsert();
            }
        });
        headerPopup.add(jmi);

        menuElements = popup.getSubElements();
        popupVec.addAll(Arrays.asList(menuElements));

        Util.debugPrint(true, "popup menu added");
        popupListener = new PopupListener();
        JP_soilLayerProp.addMouseListener(popupListener);
    }

    class PopupListener extends MouseAdapter {

        @Override
        public void mousePressed(MouseEvent e) {

            //System.out.println("Mcrew: mousepressed:");
            maybeShowPopup(e);
            Util.debugPrint(true, "mouse pressed -- current row " + GridLayrProp.getCurrentRow());
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            //System.out.println("Mcrew: released:");
            maybeShowPopup(e);
        }

        private void maybeShowPopup(MouseEvent e) {
            if (e.isPopupTrigger()) {
                e.consume();
                //Show the popup menu only when the entire row is selected - neha
                if (GridLayrProp.showPopup()) {
                    popup.show(e.getComponent(), e.getX(), e.getY());
                } else if (GridLayrProp.showHeaderPopup()) {
                    headerPopup.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        }
    }
}
