/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cobi.kgg.ui.dialog;

import cern.colt.list.DoubleArrayList;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.log4j.Logger;
import org.cobi.kgg.business.CandidateGeneExtender;
import org.cobi.kgg.business.PValuePainter;
import org.cobi.kgg.business.entity.Chromosome;
import org.cobi.kgg.business.entity.Constants;
import org.cobi.kgg.business.entity.Gene;
import org.cobi.kgg.business.entity.GeneBasedAssociation;
import org.cobi.kgg.business.entity.Genome;
import org.cobi.kgg.business.entity.PValueGene;
import org.cobi.kgg.business.entity.Pathway;
import org.cobi.kgg.business.entity.PathwayBasedAssociation;
import org.cobi.kgg.business.entity.PathwayWilcoxPValueComparator;
import org.cobi.kgg.ui.ArrayListStringArrayTableModel;
import org.cobi.util.text.Util;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.ErrorManager;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.util.Utilities;
import org.cobi.kgg.ui.GlobalManager;
import org.cobi.kgg.ui.action.BuildGenome;
import org.cobi.kgg.ui.action.ScanPathwayBasedAssociation;
import org.cobi.util.net.URLOpener;
import org.cobi.util.text.LocalExcelFile;
import org.cobi.util.text.LocalFile;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.openide.awt.StatusDisplayer;
import org.openide.util.Cancellable;
import org.openide.util.RequestProcessor;
import org.openide.windows.WindowManager;

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
/**
 * Top component which displays something.
 */
@ConvertAsProperties(
        dtd = "-//org.cobi.kgg.ui.dialog//PathwayInfo//EN",
        autostore = false)
@TopComponent.Description(
        preferredID = "PathwayInfoTopComponent",
        iconBase = "org/cobi/kgg/ui/png/16x16/Sync.png",
        persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "BioModule", id = "org.cobi.kgg.ui.dialog.PathwayInfoTopComponent")
@ActionReference(path = "Menu/BioModule", position = 433)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_PathwayInfoAction",
        preferredID = "PathwayInfoTopComponent")
@Messages({
    "CTL_PathwayInfoAction=View Genesets",
    "CTL_PathwayInfoTopComponent=View Genesets",
    "HINT_PathwayInfoTopComponent=This is a Genesets Info window"
})
public final class PathwayInfoTopComponent extends TopComponent implements LookupListener, Constants {

    private final static Logger LOG = Logger.getLogger(PathwayInfoTopComponent.class.getName());
    private Lookup.Result<PathwayBasedAssociation> pbaResult = null;
    private PathwayBasedAssociation pbaEvent = null;
    private List<String[]> lstPathwayShow;
    private ArrayListStringArrayTableModel aomPathwayTermModel;
    private final String[] strPathwayTitle = {"GeneSetID", "GeneSet_PValue_Wilcoxon", "IsSignificant_Wilcoxon", "GeneSet_PValue_HYST", "IsSignificant_HYST", "Total_GeneSet_Gene#", "GeneSet_Name", "GeneSet_URL"};
    private List<String[]> lstGeneShow;
    private ArrayListStringArrayTableModel aomGeneTermModel;
    private final String[] strGeneTitle = {"Symbol", "PValue", "IsSignificant", "Entrez", "Chromosome", "Start", "Length", "SNP#"};
    private final String[] strOutput = {"GeneSetID", "GeneSet_PValue_Wilcoxon", "IsSignificant_Wilcoxon", "GeneSet_PValue_HYST", "IsSignificant_HYST", "Total_GeneSet_Gene#", "GeneSet_Name", "GeneSet_URL", "Symbol", "PValue", "Entrez", "Chromosome", "Start", "Length", "SNP#"};
    private List<Pathway> filteredByErichmentTestPathwayList;
    List<Pathway> allPathwayList;
    private Map<String, Pathway> mapSymbol2Pathway;
    private PathwayBasedAssociation pbaCurrent;
    private Map<String, int[]> mapG2C;
    private Chromosome[] chrTerms;
    private List<PValueGene> lstPVG;
    private Map<String, Double> genePValueMap;
    private double sigPathwayGeneCutoff = 0.05;

    private boolean handleCancel() {

        if (null == theTask) {
            return false;
        }
        return theTask.cancel();
    }
    private final static RequestProcessor RP = new RequestProcessor("Loading analysis genome tas", 1, true);
    private RequestProcessor.Task theTask = null;

    public PathwayInfoTopComponent() {
        try {

            lstPathwayShow = new ArrayList();
            aomPathwayTermModel = new ArrayListStringArrayTableModel();
            aomPathwayTermModel.setTitle(strPathwayTitle);
            aomPathwayTermModel.setDataList(lstPathwayShow);

            lstGeneShow = new ArrayList();
            aomGeneTermModel = new ArrayListStringArrayTableModel();
            aomGeneTermModel.setTitle(strGeneTitle);
            aomGeneTermModel.setDataList(lstGeneShow);

            filteredByErichmentTestPathwayList = new ArrayList();
            mapSymbol2Pathway = new HashMap<String, Pathway>();

            initComponents();
            setName(Bundle.CTL_PathwayInfoTopComponent());
            setToolTipText(Bundle.HINT_PathwayInfoTopComponent());
            allPathwayList = new ArrayList<Pathway>();
        } catch (Exception ex) {
            Exceptions.printStackTrace(ex);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new JTable(aomPathwayTermModel){
            public boolean isCellEditable(int row, int column){return false;}
        };
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jPanel4 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        enrichmentTestComboBox = new javax.swing.JComboBox();
        enableCandidateGeneCheckBox = new javax.swing.JCheckBox();
        candidateGeneComboBox = new javax.swing.JComboBox();
        jLabel18 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        pathwayGenePvalueTextField = new javax.swing.JTextField();
        geneSelectionMethodComboBox = new javax.swing.JComboBox();
        jLabel13 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        refMultiTestingEnrichmentIDComboBox = new javax.swing.JComboBox();
        jLabel10 = new javax.swing.JLabel();
        pValueEnrichmentThresholdText = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        minPathwaySizeTextField = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        geneHystSigMethodComboBox = new javax.swing.JComboBox();
        jLabel8 = new javax.swing.JLabel();
        pathwayHystGeneSigPvalueTextField = new javax.swing.JTextField();
        genePvalueFilterTextField = new javax.swing.JTextField();
        applyButton = new javax.swing.JButton();
        jLabel17 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        pathwayPvalueFilterTextField = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jComboBox3 = new javax.swing.JComboBox();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                formPropertyChange(evt);
            }
        });

        jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.jScrollPane1.border.title"))); // NOI18N

        jTable1.setModel(aomPathwayTermModel);
        jTable1.setToolTipText(org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.jTable1.toolTipText")); // NOI18N
        jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jSplitPane1.setDividerLocation(150);
        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        jScrollPane2.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.jScrollPane2.border.title"))); // NOI18N

        jTable2.setModel(aomGeneTermModel);
        jTable2.setToolTipText(org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.jTable2.toolTipText")); // NOI18N
        jTable2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable2MouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(jTable2);

        jSplitPane1.setLeftComponent(jScrollPane2);

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.jPanel3.border.title"))); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.jLabel3.text")); // NOI18N

        enrichmentTestComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Wilcoxon signed-rank test" }));
        enrichmentTestComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                enrichmentTestComboBoxActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(enableCandidateGeneCheckBox, org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.enableCandidateGeneCheckBox.text")); // NOI18N
        enableCandidateGeneCheckBox.setEnabled(false);

        candidateGeneComboBox.setModel(GlobalManager.candiGeneFilesModel);
        candidateGeneComboBox.setEnabled(false);
        candidateGeneComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                candidateGeneComboBoxItemStateChanged(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel18, org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.jLabel18.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel12, org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.jLabel12.text")); // NOI18N

        pathwayGenePvalueTextField.setText(org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.pathwayGenePvalueTextField.text")); // NOI18N

        geneSelectionMethodComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Fixed p-value threshold", "Benjamini & Hochberg (1995)", "Benjamini & Yekutieli (2001)", "Standard Bonferroni" }));

        org.openide.awt.Mnemonics.setLocalizedText(jLabel13, org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.jLabel13.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel9, org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.jLabel9.text")); // NOI18N

        refMultiTestingEnrichmentIDComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Benjamini & Hochberg (1995)", "Benjamini & Yekutieli (2001)", "Standard Bonferroni" }));

        org.openide.awt.Mnemonics.setLocalizedText(jLabel10, org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.jLabel10.text")); // NOI18N

        pValueEnrichmentThresholdText.setText(org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.pValueEnrichmentThresholdText.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.jLabel4.text")); // NOI18N

        minPathwaySizeTextField.setText(org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.minPathwaySizeTextField.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel7, org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.jLabel7.text")); // NOI18N

        geneHystSigMethodComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Benjamini & Hochberg (1995)", "Benjamini & Yekutieli (2001)", "Standard Bonferroni" }));

        org.openide.awt.Mnemonics.setLocalizedText(jLabel8, org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.jLabel8.text")); // NOI18N

        pathwayHystGeneSigPvalueTextField.setText(org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.pathwayHystGeneSigPvalueTextField.text")); // NOI18N

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(jLabel13)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(geneSelectionMethodComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel12)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(pathwayGenePvalueTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(enableCandidateGeneCheckBox)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(candidateGeneComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel18))
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jLabel9)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(refMultiTestingEnrichmentIDComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel10)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(pValueEnrichmentThresholdText, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel3Layout.createSequentialGroup()
                                        .addGap(199, 199, 199)
                                        .addComponent(geneHystSigMethodComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel8)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(pathwayHystGeneSigPvalueTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(jLabel7))))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(enrichmentTestComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 239, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(23, 23, 23)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(minPathwaySizeTextField)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(enrichmentTestComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(minPathwaySizeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(enableCandidateGeneCheckBox)
                    .addComponent(candidateGeneComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel18))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel13)
                    .addComponent(jLabel12)
                    .addComponent(pathwayGenePvalueTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(geneSelectionMethodComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel9)
                    .addComponent(refMultiTestingEnrichmentIDComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10)
                    .addComponent(pValueEnrichmentThresholdText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(geneHystSigMethodComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8)
                    .addComponent(pathwayHystGeneSigPvalueTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jLabel8.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.jLabel8.AccessibleContext.accessibleName")); // NOI18N

        genePvalueFilterTextField.setText(org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.genePvalueFilterTextField.text")); // NOI18N
        genePvalueFilterTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                genePvalueFilterTextFieldKeyPressed(evt);
            }
        });

        applyButton.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        applyButton.setForeground(new java.awt.Color(255, 51, 51));
        org.openide.awt.Mnemonics.setLocalizedText(applyButton, org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.applyButton.text")); // NOI18N
        applyButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                applyButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel17, org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.jLabel17.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.jLabel1.text")); // NOI18N

        pathwayPvalueFilterTextField.setText(org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.pathwayPvalueFilterTextField.text")); // NOI18N
        pathwayPvalueFilterTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                pathwayPvalueFilterTextFieldKeyPressed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.jPanel1.border.title"))); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel5, org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.jLabel5.text")); // NOI18N

        jComboBox3.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Only Pathway", "Pathway+Gene" }));

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Excel(.xls)", "Text(.txt)", "Excel(.xlsx)" }));
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.jLabel2.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jButton1, org.openide.util.NbBundle.getMessage(PathwayInfoTopComponent.class, "PathwayInfoTopComponent.jButton1.text")); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(15, 15, 15)
                .addComponent(jLabel2)
                .addGap(23, 23, 23)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel5)
                .addGap(18, 18, 18)
                .addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31)
                .addComponent(jButton1)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel5)
                        .addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton1))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(pathwayPvalueFilterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(32, 32, 32)
                        .addComponent(jLabel17)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(genePvalueFilterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(applyButton)
                        .addContainerGap())
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(applyButton)
                    .addComponent(pathwayPvalueFilterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel17)
                    .addComponent(genePvalueFilterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jSplitPane1.setRightComponent(jPanel4);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jScrollPane1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 369, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    public void showGenes(int intSelectedRow) throws Exception {
        List<String[]> lstCurrentPathway = aomPathwayTermModel.getDataList();
        Pathway phySelectedPathway = mapSymbol2Pathway.get(lstCurrentPathway.get(intSelectedRow)[0]);
        Set<String> setGenes = phySelectedPathway.getGeneSymbolWeightMap().keySet();//The keys are not the whole. 
        List<String> lstPVSource = pbaCurrent.getpValueSources();

        double genePValueExport = Double.valueOf(genePvalueFilterTextField.getText());

        lstGeneShow.clear();
        for (Iterator itrGene = setGenes.iterator(); itrGene.hasNext();) {
            String[] strGeneInfos;
            String strSymbol = (String) itrGene.next();
            int[] intPositions = mapG2C.get(strSymbol);
            if (intPositions == null) {
                continue;
            }
            Gene gneTerm = chrTerms[intPositions[0]].genes.get(intPositions[1]);
            double p = genePValueMap.get(strSymbol);
            if (p > genePValueExport) {
                continue;
            }
            strGeneInfos = new String[]{strSymbol, Util.formatPValue(p), p <= sigPathwayGeneCutoff ? "Y" : "N", String.valueOf(gneTerm.getEntrezID()), chrTerms[intPositions[0]].getName(), String.valueOf(gneTerm.getStart()), String.valueOf(gneTerm.getEnd() - gneTerm.getStart() + 1), String.valueOf(gneTerm.snps.size())};
            lstGeneShow.add(strGeneInfos);
        }
        aomGeneTermModel.setDataList(lstGeneShow);
        aomGeneTermModel.fireTableDataChanged();

    }

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        try {
            int intSelectedRow = jTable1.getSelectedRow();
            List<String[]> lstCurrentPathway = aomPathwayTermModel.getDataList();
            Pathway phySelectedPathway = mapSymbol2Pathway.get(lstCurrentPathway.get(intSelectedRow)[0]);
            if (evt.getClickCount() == 1) {
                if (intSelectedRow >= 0) {
                    showGenes(intSelectedRow);
                }
            } else {
                String id = phySelectedPathway.getID();
                URLOpener.openURL("http://www.broadinstitute.org/gsea/msigdb/geneset_page.jsp?geneSetName=" + id);
            }

        } catch (Exception ex) {
            Exceptions.printStackTrace(ex);
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            TopComponent outputWindow = WindowManager.getDefault().findTopComponent("AnalysisOutputTopComponent");
            //Determine if it is opened
            if (outputWindow != null && !outputWindow.isOpened()) {
                outputWindow.open();
            }
            List<String[]> lstOutput = new ArrayList();
            List<String[]> lstCurrentPathway = aomPathwayTermModel.getDataList();
            String strContent = jComboBox3.getSelectedItem().toString();
            //String strFormat = jComboBox1.getSelectedItem().toString();
            JFileChooser jfcSave = null;
            if ((GlobalManager.lastAccessedPath != null) && (GlobalManager.lastAccessedPath.trim().length() > 0)) {
                jfcSave = new JFileChooser(GlobalManager.lastAccessedPath);
            } else {
                jfcSave = new JFileChooser();
            }
            jfcSave.setDialogTitle("Save " + strContent);
            FileNameExtensionFilter fnefFilter = null;
            if (jComboBox1.getSelectedIndex() == 0) {
                fnefFilter = new FileNameExtensionFilter("*.xls", "xls");
            } else if (jComboBox1.getSelectedIndex() == 1) {
                fnefFilter = new FileNameExtensionFilter("*.txt", "txt");
            } else {
                fnefFilter = new FileNameExtensionFilter("*.xlsx", "xlsx");
            }
            jfcSave.setFileFilter(fnefFilter);
            int intResult = jfcSave.showSaveDialog(this);
            File fleFile = jfcSave.getSelectedFile();
            if (intResult == JFileChooser.APPROVE_OPTION) {
                if (jComboBox1.getSelectedIndex() == 0) {
                    if (!fleFile.getPath().endsWith("xls")) {
                        fleFile = new File(fleFile.getPath() + ".xls");
                    }
                } else if (jComboBox1.getSelectedIndex() == 1) {
                    if (!fleFile.getPath().endsWith("txt")) {
                        fleFile = new File(fleFile.getPath() + ".txt");
                    }
                } else {
                    if (!fleFile.getPath().endsWith("xlsx")) {
                        fleFile = new File(fleFile.getPath() + ".xlsx");
                    }
                }
                GlobalManager.lastAccessedPath = fleFile.getParent();
            } else {
                return;
            }

            if (jComboBox3.getSelectedIndex() == 1) {
                for (String[] strPathway : lstCurrentPathway) {
                    Pathway phyCurrentPathway = mapSymbol2Pathway.get(strPathway[0]);
                    if (phyCurrentPathway == null) {
                        continue;
                    }
                    Set<String> setGenes = phyCurrentPathway.getGeneSymbolWeightMap().keySet();
                    boolean boolOpen = true;
                    for (Iterator itrGene = setGenes.iterator(); itrGene.hasNext();) {
                        String[] strGeneInfos;
                        String strSymbol = (String) itrGene.next();
                        int[] intPositions = mapG2C.get(strSymbol);
                        if (intPositions == null) {
                            continue;
                        }
                        Gene gneTerm = chrTerms[intPositions[0]].genes.get(intPositions[1]);
                        strGeneInfos = new String[]{strSymbol, Util.formatPValue(genePValueMap.get(strSymbol)), String.valueOf(gneTerm.getEntrezID()), chrTerms[intPositions[0]].getName(), String.valueOf(gneTerm.getStart()), String.valueOf(gneTerm.getEnd() - gneTerm.getStart() + 1), String.valueOf(gneTerm.snps.size())};
                        String[] strRow = new String[strPathway.length + strGeneInfos.length];
                        if (boolOpen) {
                            System.arraycopy(strPathway, 0, strRow, 0, strPathway.length);
                            System.arraycopy(strGeneInfos, 0, strRow, strPathway.length, strGeneInfos.length);
                            boolOpen = false;
                        } else {
                            System.arraycopy(strGeneInfos, 0, strRow, strPathway.length, strGeneInfos.length);
                        }
                        lstOutput.add(strRow);
                    }
                }
                lstOutput.add(0, strOutput);
            } else {
                lstOutput = lstCurrentPathway;
                lstOutput.add(0, strPathwayTitle);
            }

            if (fleFile.getName().endsWith("xls")) {
                LocalExcelFile.writeArray2ExcelFile(fleFile.getCanonicalPath(), lstOutput, false);
            } else if (fleFile.getName().endsWith("txt")) {
                LocalFile.writeData(fleFile.getCanonicalPath(), lstOutput, "\t", false);
            } else {
                LocalExcelFile.WriteArray2XLSXFile(fleFile.getCanonicalPath(), lstOutput, false);
            }

            if (fleFile.exists()) {
                JOptionPane.showMessageDialog(this, "The data have has been saved in " + fleFile.getCanonicalPath() + ".", "File Infomation", JOptionPane.CLOSED_OPTION);
            }
        } catch (Exception ex) {
            Exceptions.printStackTrace(ex);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void jTable2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable2MouseClicked
        if (evt.getClickCount() == 2) {
            int intRow = jTable1.getSelectedRow();
            String strTarget = (String) jTable2.getValueAt(intRow, 0);

            URLOpener.openURL("http://www.genecards.org/cgi-bin/carddisp.pl?gene=" + strTarget);
        }
    }//GEN-LAST:event_jTable2MouseClicked

    private void pathwayPvalueFilterTextFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_pathwayPvalueFilterTextFieldKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            String strER = pathwayPvalueFilterTextField.getText();
            double dblER;
            if ("".equals(strER)) {
                pathwayPvalueFilterTextField.setText("0.05");
                dblER = 0.05;
            } else {
                dblER = Double.valueOf(strER);
            }

            List<String[]> lstCurrentPathway = aomPathwayTermModel.getDataList();
            List<String[]> lstNewPathway = new ArrayList();
            for (String[] strTerm : lstCurrentPathway) {
                if (Double.valueOf(strTerm[1]) < dblER) {
                    lstNewPathway.add(strTerm);
                }
            }
            aomPathwayTermModel.setDataList(lstNewPathway);
            aomPathwayTermModel.fireTableDataChanged();
        }
    }//GEN-LAST:event_pathwayPvalueFilterTextFieldKeyPressed
    private void genePvalueFilterTextFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_genePvalueFilterTextFieldKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            String strER = genePvalueFilterTextField.getText();
            double dblER;
            if ("".equals(strER)) {
                genePvalueFilterTextField.setText("0.05");
                dblER = 0.05;
            } else {
                dblER = Double.valueOf(strER);
            }

            List<String[]> lstCurrentGene = aomGeneTermModel.getDataList();
            List<String[]> lstNewGene = new ArrayList();
            for (Iterator itrTerm = lstCurrentGene.iterator(); itrTerm.hasNext();) {
                String[] strTerm = (String[]) itrTerm.next();
                if (Double.valueOf(strTerm[1]) < dblER) {
                    lstNewGene.add(strTerm);
                }
            }
            aomGeneTermModel.setDataList(lstNewGene);
            aomGeneTermModel.fireTableDataChanged();
        }
    }//GEN-LAST:event_genePvalueFilterTextFieldKeyPressed


    private void candidateGeneComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_candidateGeneComboBoxItemStateChanged


    }//GEN-LAST:event_candidateGeneComboBoxItemStateChanged

    private void applyButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_applyButtonActionPerformed
        if (GlobalManager.isLoadingGenome) {
            String infor = "Be patient! I am loading the LD data!";
            JOptionPane.showMessageDialog(this, infor, "Warnning", JOptionPane.WARNING_MESSAGE);
            return;
        }

        TopComponent outputWindow = WindowManager.getDefault().findTopComponent("AnalysisOutputTopComponent");
        //Determine if it is opened
        if (outputWindow != null && !outputWindow.isOpened()) {
            outputWindow.open();
        }
        ApplySettingSwingWorker loader = new ApplySettingSwingWorker();
        theTask = RP.create(loader); //the task is not started yet
        theTask.schedule(0); //start the task

    }//GEN-LAST:event_applyButtonActionPerformed

    private void enrichmentTestComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enrichmentTestComboBoxActionPerformed
        String testName = enrichmentTestComboBox.getSelectedItem().toString();
        if (testName.equals("Hypergeometric test")) {
            enableCandidateGeneCheckBox.setEnabled(true);
            geneSelectionMethodComboBox.setEnabled(true);
            pathwayGenePvalueTextField.setEnabled(true);
        } else {
            enableCandidateGeneCheckBox.setEnabled(false);
            geneSelectionMethodComboBox.setEnabled(false);
            pathwayGenePvalueTextField.setEnabled(false);
        }

    }//GEN-LAST:event_enrichmentTestComboBoxActionPerformed

    private void formPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_formPropertyChange


    }//GEN-LAST:event_formPropertyChange

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton applyButton;
    private javax.swing.JComboBox candidateGeneComboBox;
    private javax.swing.JCheckBox enableCandidateGeneCheckBox;
    private javax.swing.JComboBox enrichmentTestComboBox;
    private javax.swing.JComboBox geneHystSigMethodComboBox;
    private javax.swing.JTextField genePvalueFilterTextField;
    private javax.swing.JComboBox geneSelectionMethodComboBox;
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextField minPathwaySizeTextField;
    private javax.swing.JTextField pValueEnrichmentThresholdText;
    private javax.swing.JTextField pathwayGenePvalueTextField;
    private javax.swing.JTextField pathwayHystGeneSigPvalueTextField;
    private javax.swing.JTextField pathwayPvalueFilterTextField;
    private javax.swing.JComboBox refMultiTestingEnrichmentIDComboBox;
    // End of variables declaration//GEN-END:variables

    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
        pbaResult = Utilities.actionsGlobalContext().lookupResult(PathwayBasedAssociation.class);
        pbaResult.addLookupListener(this);
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
        pbaResult.removeLookupListener(this);
        pbaResult = null;
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    class LoadGenomeDataSwingWorker extends SwingWorker<Void, String> {

        PathwayBasedAssociation pbaCurrent;

        boolean succeed = false;
        ProgressHandle ph = null;

        public LoadGenomeDataSwingWorker(PathwayBasedAssociation event) {
            ph = ProgressHandleFactory.createHandle("Loading analysis genome task", new Cancellable() {
                @Override
                public boolean cancel() {
                    return handleCancel();
                }
            });
            ph.start(); //we must start the PH before we swith to determinate
            ph.switchToIndeterminate();
            this.pbaCurrent = event;
        }

        @Override
        protected Void doInBackground() {
            try {
                GlobalManager.isLoadingGenome = true;
                publish("Loading analysis genomes.... Please wait for a while!");

                GeneBasedAssociation gbaCurrent = pbaCurrent.getGeneScan();
                Genome gnmGenome = gbaCurrent.getGenome();
                mapG2C = gnmGenome.loadGeneGenomeIndexes2Buf();
              
                chrTerms = gnmGenome.loadAllChromosomes2Buf();
              

                lstPVG = pbaCurrent.getGeneScan().loadGenePValuesfromDisk(pbaEvent.getpValueSources().get(0));
                allPathwayList.clear();

                allPathwayList.addAll(pbaEvent.loadPathwayAssociation(pbaEvent.getpValueSources().get(0)));

                // Collections.sort(allPathwayList, new PathwayWilcoxPValueComparator());//Is it right?
                //do multiple testing and show genes in the tables 
                showPathwaysInTable(allPathwayList);
                publish("Analysis genome have been loaded!");
                if (aomPathwayTermModel.getRowCount() > 0) {
                    showGenes(0);
                }
               

            } catch (InterruptedException ex) {
                StatusDisplayer.getDefault().setStatusText("Building analysis genome task was CANCELLED!");
                java.util.logging.Logger.getLogger(BuildGenome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (Exception ex) {
                ex.printStackTrace();
                StatusDisplayer.getDefault().setStatusText("Building analysis genome task was CANCELLED!");
                java.util.logging.Logger.getLogger(BuildGenome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
           
            succeed = true;
            GlobalManager.isLoadingGenome = false;
            return null;
        }

        @Override
        protected void process(List<String> chunks) {
            // TODO Auto-generated method stub  
            for (String message : chunks) {
                LOG.info(message);
                StatusDisplayer.getDefault().setStatusText(message);
            }
        }

        @Override
        protected void done() {
            try {
                String message;
                ph.finish();
                GlobalManager.isLoadingGenome = false;
            } catch (Exception e) {
                ErrorManager.getDefault().notify(e);
            }
        }
    }

    class ApplySettingSwingWorker extends SwingWorker<Void, String> {

        boolean succeed = false;
        ProgressHandle ph = null;

        public ApplySettingSwingWorker() {
            ph = ProgressHandleFactory.createHandle("Loading analysis genome task", new Cancellable() {
                @Override
                public boolean cancel() {
                    return handleCancel();
                }
            });
            ph.start(); //we must start the PH before we swith to determinate
            ph.switchToIndeterminate();
        }

        @Override
        protected Void doInBackground() {
            try {

                GlobalManager.isLoadingGenome = true;
                publish("Loading analysis genomes.... Please wait for a while!");

                showPathwaysInTable(allPathwayList);
                if (aomPathwayTermModel.getRowCount() > 0) {
                    showGenes(0);
                }
                 

            } catch (InterruptedException ex) {
                StatusDisplayer.getDefault().setStatusText("Applying seting task was CANCELLED!");
                java.util.logging.Logger.getLogger(BuildGenome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (Exception ex) {
                ex.printStackTrace();
                StatusDisplayer.getDefault().setStatusText("Applying seting task was CANCELLED!");
                java.util.logging.Logger.getLogger(BuildGenome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //  ph.progress(100);
            succeed = true;
            return null;
        }

        @Override
        protected void process(List<String> chunks) {
            // TODO Auto-generated method stub  
            for (String message : chunks) {
                LOG.info(message);
                StatusDisplayer.getDefault().setStatusText(message);
            }
        }

        @Override
        protected void done() {
            try {
                String message;
                if (succeed) {

                }
                ph.finish();
                GlobalManager.isLoadingGenome = false;
            } catch (Exception e) {
                ErrorManager.getDefault().notify(e);
            }
        }
    }

    @Override
    public void resultChanged(LookupEvent le) {
        Collection<? extends PathwayBasedAssociation> allEvents = pbaResult.allInstances();
        try {
            if (!allEvents.isEmpty()) {
                pbaEvent = allEvents.iterator().next();
                this.open();
                this.requestActive();
                if (pbaEvent != null && pbaEvent instanceof PathwayBasedAssociation) {
                    pbaCurrent = pbaEvent;
                    if (GlobalManager.isLoadingGenome) {
                        String infor = "Be patient! I am loading the analysis genome!";
                        JOptionPane.showMessageDialog(this, infor, "Warnning", JOptionPane.WARNING_MESSAGE);
                        return;
                    }
                    LoadGenomeDataSwingWorker loader = new LoadGenomeDataSwingWorker(pbaCurrent);

                    theTask = RP.create(loader); //the task is not started yet
                    theTask.schedule(0); //start the task
                }

            }
        } catch (Exception ex) {
            ErrorManager.getDefault().notify(ex);
        }
    }

    private void showPathwaysInTable(List<Pathway> orgPathwayList) throws Exception {
        CandidateGeneExtender cgeRead = new CandidateGeneExtender();
        Set<String> canidateGene = null;
        if (enableCandidateGeneCheckBox.isSelected()) {
            int selectCanidateGene = candidateGeneComboBox.getSelectedIndex();
            File fleCandidate = null;
            if (selectCanidateGene >= 0) {
                //FileTextNode ftnRoot = new FileTextNode(GlobalManager.currentProject.getWorkingPath() + GlobalManager.currentProject.getName() + "\\candidate_genes");
                fleCandidate = (File) candidateGeneComboBox.getSelectedItem();
                // File fleFile = new File(ftnRoot.getPath() + "\\" + fleCandidate.getPath());
                cgeRead.readSeedGenesFromFile(fleCandidate);
                canidateGene = cgeRead.getSeedGeneSet();
            }
        }

        genePValueMap = new HashMap<String, Double>();
        for (PValueGene pvgTerm : lstPVG) {
            genePValueMap.put(pvgTerm.getSymbol(), pvgTerm.getpValue());
        }
        // pbaCurrent.setPathwayMultipleTestingMethod(refMultiTestingHystIDComboBox.getSelectedItem().toString());
        //  pbaCurrent.setPathwayMultipleTestingPValue(Double.valueOf(pValueHystThresholdText.getText()));
        pbaCurrent.setPathwayEnrichmentMultipleTestingMethod(refMultiTestingEnrichmentIDComboBox.getSelectedItem().toString());
        pbaCurrent.setPathwayEnrichmentMultipleTestingPValue(Double.valueOf(pValueEnrichmentThresholdText.getText()));

        pbaCurrent.setPathwayGeneMultipleTestingMethod(geneHystSigMethodComboBox.getSelectedItem().toString());
        pbaCurrent.setPathwayGeneMultipleTestingPValue(Double.valueOf(pathwayHystGeneSigPvalueTextField.getText()));

        pbaCurrent.setGeneHyperSignifMethod(geneSelectionMethodComboBox.getSelectedItem().toString());
        pbaCurrent.setGeneHyperSignifPValueCutoff(Double.parseDouble(pathwayGenePvalueTextField.getText()));
        pbaCurrent.setFilterNonSigEnriched(false);
        ScanPathwayBasedAssociation spbaResult = new ScanPathwayBasedAssociation(pbaCurrent, null);
        spbaResult.setPruningMethod(enrichmentTestComboBox.getSelectedItem().toString());

        /*
         DoubleArrayList pathwayPValueHyst = null;
         if (!removeOverLappedGeneCheckBox.isSelected()) {
         Collections.sort(orgPathwayList, new PathwayWilcoxPValueComparator());
         pathwayPValueHyst = new DoubleArrayList();
         Iterator<Pathway> itrPathway = orgPathwayList.iterator();
         while (itrPathway.hasNext()) {
         Pathway phyTerm = itrPathway.next();
         pathwayPValueHyst.add(phyTerm.getHystPValue());
         }
         pathwayPValueHyst.quickSort();
         } else {
         int size = orgPathwayList.size();
         Collections.sort(orgPathwayList, new PathwayWilcoxPValueComparator());
         for (int i = 0; i < size; i++) {
         orgPathwayList.get(i).setRank(i);
         }
         Collections.sort(orgPathwayList, new PathwayEnrichedPValueComparator());
         for (int i = 0; i < size; i++) {
         orgPathwayList.get(i).setRank(orgPathwayList.get(i).getRank() + i);
         }
         Collections.sort(orgPathwayList, new PathwayRankComparator());
         //by default we use the firt source. but this may be changed later
         String sourcePValueName = pbaEvent.getpValueSources().get(0);

         List<PValueGene> geneList = pbaCurrent.getGeneScan().loadGenePValuesfromDisk(sourcePValueName);
         Map<String, PValueGene> genePValueMapLocal = new HashMap<String, PValueGene>();
         int geneNum = geneList.size();
         for (int i = 0; i < geneNum; i++) {
         genePValueMapLocal.put(geneList.get(i).getSymbol(), geneList.get(i));
         // allGenepValues.add(geneList.get(i).pValue);
         }

         }
         */
        Collections.sort(orgPathwayList, new PathwayWilcoxPValueComparator());
        int minPathwaySize = Integer.parseInt(minPathwaySizeTextField.getText());
        DoubleArrayList pathwayPValueHyper = spbaResult.hypergeometricPathwayTest(lstPVG, orgPathwayList, canidateGene, minPathwaySize);
        pathwayPValueHyper.quickSort();

        //DoubleArrayList pathwayPValueWilcoxon = spbaResult.wilcoxonTestExistingPathway(genePValueMap, orgPathwayList, minPathwaySize);
        DoubleArrayList pathwayPValueWilcoxon = new DoubleArrayList();
        DoubleArrayList pathwayPValueHyst = new DoubleArrayList();
        for (Pathway pathway : orgPathwayList) {
            pathwayPValueWilcoxon.add(pathway.getWilcoxonPValue());
            pathwayPValueHyst.add(pathway.getHystPValue());
        }
        pathwayPValueWilcoxon.quickSort();
        pathwayPValueHyst.quickSort();
        String prjWorkingPath = GlobalManager.currentProject.getWorkingPath();
        String prjName = GlobalManager.currentProject.getName();

        File imgFolder = new File(prjWorkingPath + File.separator + prjName + File.separator + "image" + File.separator);
        if (!imgFolder.exists()) {
            imgFolder.mkdirs();
        }
        File imgFile = new File(imgFolder.getCanonicalPath() + File.separator + pbaEvent.getName() + "." + "QQPlotGeneSetP" + ".png");
        List<String> titles = new ArrayList<String>();
        List<DoubleArrayList> pvalueList = new ArrayList<DoubleArrayList>();
        //it seems that the Hypergeometric test is NOT suitable for QQ plot

        //  titles.add("HYST Set-based test");
        //   pvalueList.add(pathwayPValueHyst);
        if (spbaResult.getPruningMethod().startsWith("Hypergeometric test")) {

        } else {
            //Wilcoxon signed-rank test

        }
        //titles.add("Hypergeometric test");
        // pvalueList.add(pathwayPValueHyper);
        titles.add("HYST for gene-set");
        pvalueList.add(pathwayPValueHyst);
        titles.add("Wilcoxon test");
        pvalueList.add(pathwayPValueWilcoxon);

        PValuePainter painter = new PValuePainter(600, 400);
        painter.drawMultipleQQPlot(pvalueList, titles, null, imgFile.getCanonicalPath(), 1E-35);

        pvalueList.clear();

        ShowPlotDialog cpDialog = new ShowPlotDialog();
        cpDialog.setLocationRelativeTo(GlobalManager.mainFrame);
        cpDialog.setVisible(true);
        cpDialog.insertImage2PlottingPane(imgFile);

        double[] adjustePCutoffs = new double[3];
        filteredByErichmentTestPathwayList.clear();
        filteredByErichmentTestPathwayList.addAll(orgPathwayList);
        StringBuilder sbInfor = new StringBuilder();
        sigPathwayGeneCutoff = spbaResult.significanceTest(filteredByErichmentTestPathwayList, pathwayPValueHyst, pathwayPValueHyper, pathwayPValueWilcoxon, genePValueMap, adjustePCutoffs, sbInfor);
        cpDialog.insertText2PlottingPane(sbInfor.toString());

        pathwayPValueHyper.clear();
        pathwayPValueWilcoxon.clear();

        double pathwayPValueExport = Double.valueOf(pathwayPvalueFilterTextField.getText());

        Double gp = null;

        lstPathwayShow.clear();
        // remove pathways with large p-values to export
        List<Pathway> tmpPahtwayList = new ArrayList<Pathway>();
        Iterator<Pathway> itrPathway = filteredByErichmentTestPathwayList.iterator();
        mapSymbol2Pathway.clear();
        while (itrPathway.hasNext()) {
            Pathway phyTerm = itrPathway.next();
            if (phyTerm.getWilcoxonPValue() <= pathwayPValueExport) {
                tmpPahtwayList.add(phyTerm);
                mapSymbol2Pathway.put(phyTerm.getID(), phyTerm);
              
                String[] strTerm = new String[]{phyTerm.getID(),
                    Util.formatPValue(phyTerm.getWilcoxonPValue()), phyTerm.getWilcoxonPValue() <= adjustePCutoffs[2] ? "Y" : "N",
                    Util.formatPValue(phyTerm.getHystPValue()), phyTerm.getHystPValue() <= adjustePCutoffs[0] ? "Y" : "N", String.valueOf(phyTerm.getTotalGeneNum()),
                    phyTerm.getName(), "http://www.broadinstitute.org/gsea/msigdb/geneset_page.jsp?geneSetName=" + phyTerm.getID()};

                lstPathwayShow.add(strTerm);
            }
        }

        filteredByErichmentTestPathwayList.clear();
        filteredByErichmentTestPathwayList.addAll(tmpPahtwayList);

        tmpPahtwayList.clear();

        aomPathwayTermModel.setDataList(lstPathwayShow);
        aomPathwayTermModel.fireTableDataChanged();
        String info = "";

        if (filteredByErichmentTestPathwayList.isEmpty()) {
            info = "No enriched pathways in gene-set database with association p-value <=" + pathwayPValueExport;
            LOG.info(info);
            Logger logOutput = Logger.getRootLogger();
            logOutput.info(info);
            if (GlobalManager.aotcWindow != null) {
                GlobalManager.aotcWindow.insertMessage(info);
            }

        } else {
            /*
             String infor = null;
             infor = generatePathwayStringAnnoation(filteredByErichmentTestPathwayList, adjustePCutoffs[0],
             adjustePCutoffs[0], genePValueMap, geneGenomeIndexes, canidateGene,
             prefixURLLink, null, pathwayBasedAssociation.isFilterNonSigEnriched());
             */
            // LOG.info(info);

        }

    }

}
