/*
 * StemAndLeafPlotDialog.java
 *
 * Created on December 2, 2008, 3:38 PM
 */

package org.statcato.dialogs.graph;

import org.statcato.*;
import org.statcato.spreadsheet.*;
import org.statcato.utils.HelperFunctions;
import org.statcato.utils.NumDataset;
import org.statcato.graph.StemAndLeafPlot;
import org.statcato.statistics.BasicStatistics;
import java.util.*;


/**
 * A dialog for creating stem-and-leaf plots.
 * 
 * @author Margaret Yau
 * @version %I%, %G%
 * @since 1.0
 */
public class StemAndLeafPlotDialog extends StatcatoDialog {
    
    /** Creates new form StemAndLeafPlotDialog */
    public StemAndLeafPlotDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        this.app = (Statcato) parent;
        ParentSpreadsheet = app.getSpreadsheet();
        initComponents();
        
        ParentSpreadsheet.populateColumnsList(InputVarList);
        ParentSpreadsheet.populateComboBox(GroupByComboBox);
        
        getRootPane().setDefaultButton(OKButton);
        setHelpFile("graph-stemplot");
        name = "Stem-and-Leaf Plot";
        description = "For creating stem-and-leaf-plots, which " +
                "divide each data value into a stem and a leaf " +
                "and show the leaves corresponding to each distinct " +
                "stem in the data set in a tabular fashion.";
        helpStrings.add("Select the columns containing data values. " +
                "Control-click to select multiple variables. ");
        helpStrings.add("<html>Enter the leaf unit (must be equal to 10<sup>x</sup>, " +
                "where x is an integer).</html>");
        helpStrings.add("Select the Exclude outliers checkbox to exclude " +
                "the outliers from the plot.");
        helpStrings.add("Select the Display stems that have no leaves " +
                "checkbox to display the stems with no leaves.");
        pack();
    }
    
    /**
     * Updates elements on the dialog so that they have the most
     * current values.  Called by {@link #setVisible} to make
     * sure the dialog displays current values when made visible again.
     * 
     * @see #setVisible(boolean)
     */
    @Override
    public void updateElements() {
        updateComboBox(GroupByComboBox);
        updateColumnsList(InputVarList);        
    }
    
    /** 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() {

        jPanel2 = new javax.swing.JPanel();
        OutlierCheckBox = new javax.swing.JCheckBox();
        jLabel3 = new javax.swing.JLabel();
        LeafUnitTextField = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        DisplayCheckBox = new javax.swing.JCheckBox();
        jPanel1 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        InputVarList = new javax.swing.JList();
        GroupByComboBox = new javax.swing.JComboBox();
        OKButton = new javax.swing.JButton();
        CancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Stem-and-Leaf Plot");

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Graph Options"));

        OutlierCheckBox.setSelected(true);
        OutlierCheckBox.setText("Exclude outliers");

        jLabel3.setText("Leaf unit:");

        jLabel5.setText("<html>e.g. With a leaf unit of 1, the leaf of 23 is 3.<br>\nWith a leaf unit of 0.1, the leaf of 5.6 is 6.</html>");

        jLabel6.setText("[automatic if left blank]");

        DisplayCheckBox.setSelected(true);
        DisplayCheckBox.setText("Display stems that have no leaves");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(40, 40, 40)
                        .addComponent(jLabel5))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(OutlierCheckBox)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(LeafUnitTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel6))
                            .addComponent(DisplayCheckBox))))
                .addContainerGap(23, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(LeafUnitTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5)
                .addGap(18, 18, 18)
                .addComponent(OutlierCheckBox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(DisplayCheckBox)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Graph Variables"));

        jLabel4.setText("Grouped By Categories in: [optional]");

        jLabel2.setText("Ctrl-click to select multiple variables");

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel1.setText("Graph Variables:");

        jScrollPane1.setViewportView(InputVarList);

        GroupByComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                GroupByComboBoxItemStateChanged(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()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2)
                        .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(GroupByComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(99, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(GroupByComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        OKButton.setText("OK");
        OKButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OKButtonActionPerformed(evt);
            }
        });

        CancelButton.setText("Cancel");
        CancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(83, 83, 83)
                        .addComponent(OKButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(CancelButton)))
                .addContainerGap(10, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {CancelButton, OKButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 271, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(OKButton)
                    .addComponent(CancelButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

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

    }//GEN-LAST:event_GroupByComboBoxItemStateChanged

    private void OKButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OKButtonActionPerformed
        app.compoundEdit = new DialogEdit("stem-and-leaf plot");
        
        // get selected input variables
        Object[] SelectedColumns = InputVarList.getSelectedValues();
        int[] columnNumbers = ParentSpreadsheet.convertColumnLabelsToNumbers(SelectedColumns);
        
        // check that at least one input variable is selected
        if (columnNumbers.length == 0) {
            app.showErrorDialog("Select at least one input variable.");
            return;
        }
        
        String text = "";
        
        // check if using a group by variable
        String byVarLabel = GroupByComboBox.getSelectedItem().toString();
        int byVarColNum = -1;   // BY variable column number
        Vector<Cell> byVarColVector = null;   // BY variable column vector
        boolean hasByVar = false;

        NumDataset dataset = new NumDataset();
        
        if (!byVarLabel.equals("")) { // has BY variable
            text += "Group By variable: " + byVarLabel + "<br>";
            hasByVar = true;
            byVarColNum = ParentSpreadsheet.parseColumnNumber(byVarLabel);
            byVarColVector = ParentSpreadsheet.getColumn(byVarColNum); 
            byVarColVector = HelperFunctions.removeNullCells(byVarColVector);
        }
        
        // build dataset
        text += "Graph variables: ";
        for (int i = 0; i < columnNumbers.length; ++i) {
            Vector<Cell> StrColumnVector = ParentSpreadsheet.getColumn(columnNumbers[i]);
            String columnLabel = (String) SelectedColumns[i];
            text += columnLabel + " ";
            // get input column of doubles
            Vector<Double> ColumnVector = HelperFunctions.ConvertInputVectorToDoubles(StrColumnVector);
            ColumnVector = HelperFunctions.removeNullValues(ColumnVector);
            if (ColumnVector == null) {
                app.showErrorDialog("Invalid input column " + columnLabel +
                    ": all data must be numbers.");
                return;
            }   
            
            if (hasByVar) {
                if (ColumnVector.size() != byVarColVector.size()) {
                    app.showErrorDialog("There must be one category label for " +
                            "each data value.");
                    return;
                }
                dataset.addDataVectorWithByVarLabels(ColumnVector, byVarColVector);
            }
            else
                dataset.add(ColumnVector, columnLabel);
        }
        
        double leafUnit = -1;
        if (!LeafUnitTextField.getText().equals("")) {
            // get leaf unit from text field
            try {
                double u = Double.parseDouble(LeafUnitTextField.getText());
                if (u <= 0 || Math.log10(u) - Math.floor(Math.log10(u)) != 0) {
                    throw new NumberFormatException();
                }
                leafUnit = u;
            }
            catch (NumberFormatException e) {
                app.showErrorDialog("Enter a valid number for the leaf unit.");
                return;
            }
        }
        
        text += "<br>";
        Vector<Vector<Double>> data = dataset.getValues();
        Vector<String> labels = dataset.getLabels();
        for (int i = 0; i < data.size(); ++i) {
            text += "<br>Graph Variable: " + labels.elementAt(i) + "<br>";
            // remove outliers
            if (OutlierCheckBox.isSelected()) {
                Vector<Double> outliers = 
                        BasicStatistics.removeOutliers(data.elementAt(i));
                text += "Outliers: " + 
                        HelperFunctions.printDoubleVectorToString(outliers) 
                        + "<br>";
            }
            StemAndLeafPlot plot = new StemAndLeafPlot(data.elementAt(i), leafUnit);     
            plot.displayEmptyStem = DisplayCheckBox.isSelected();
            text += "Leaf units: " + plot.getLeafUnits() + "<br>";
            text += plot;
        }
        
        app.addLogParagraph("Stem-and-Leaf Plot", text);
        
        app.compoundEdit.end();
        app.addCompoundEdit(app.compoundEdit);
        
        setVisible(false);
    }//GEN-LAST:event_OKButtonActionPerformed

    private void CancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelButtonActionPerformed
        setVisible(false);
    }//GEN-LAST:event_CancelButtonActionPerformed

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton CancelButton;
    private javax.swing.JCheckBox DisplayCheckBox;
    private javax.swing.JComboBox GroupByComboBox;
    private javax.swing.JList InputVarList;
    private javax.swing.JTextField LeafUnitTextField;
    private javax.swing.JButton OKButton;
    private javax.swing.JCheckBox OutlierCheckBox;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
    
}
