/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * RankCorrelationDialog.java
 *
 * Created on Jan 28, 2010, 10:29:16 AM
 */

package org.statcato.dialogs.stat.nonparametrics;

import org.statcato.*;
import org.statcato.spreadsheet.*;
import org.statcato.utils.HelperFunctions;
import org.statcato.statistics.inferential.nonparametrics.RankCorrelation;

import java.util.*;
import javax.swing.*;

/**
 * A dialog for Spearman's rank correlation.
 * Allows the user to specify the two variables and
 * significance level.  Computes Spearman's rank correlation coefficient,
 * critical value, and p-Value.  Displays results in the log window.
 *
 * @author  Margaret Yau
 * @version %I%, %G%
 * @see org.statcato.statistics.inferential.nonparametrics.RankCorrelation
 * @since 1.0
 */
public class RankCorrelationDialog extends StatcatoDialog {

    /** Creates new form RankCorrelationDialog */
    public RankCorrelationDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        app = (Statcato)parent;
        ParentSpreadsheet = app.getSpreadsheet();

        customInitComponents();

        setHelpFile("stat-nonparam-rank-correlation");
        name = "Rank Correlation";
        description = "For performing the Spearman's rank correlation test "
                + "between two variables.";
        helpStrings.add("Provide the matched pairs in " +
                "two separate columns and add the series of two variables to " +
                "the list of variable series.");
        helpStrings.add("Provide the significance level.");
    }

    private void customInitComponents() {
        updateComboBox(XComboBox);
        updateComboBox(YComboBox);
        clearMutableColumnsList(SeriesList);
        getRootPane().setDefaultButton(OKButton);
    }

    /**
     * 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(XComboBox);
        updateComboBox(YComboBox);
        clearMutableColumnsList(SeriesList);
    }

    /** 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        SeriesList = new JList(new DefaultListModel());
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        XComboBox = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        YComboBox = new javax.swing.JComboBox();
        AddButton = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        RemoveButton = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        SigTextField = new javax.swing.JTextField();
        OKButton = new javax.swing.JButton();
        CancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Spearman's Rank Correlation");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Inputs"));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel1.setText("Variable series");

        SeriesList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                SeriesListValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(SeriesList);

        jLabel2.setText("<html>Select the two variables of a new series:");

        jLabel3.setText("Variable 1:");

        XComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                XComboBoxItemStateChanged(evt);
            }
        });

        jLabel4.setText("Variable 2:");

        YComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                YComboBoxItemStateChanged(evt);
            }
        });

        AddButton.setText("Add Series");
        AddButton.setEnabled(false);
        AddButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddButtonActionPerformed(evt);
            }
        });

        jLabel9.setText("Select the series to be removed:");

        RemoveButton.setText("Remove Series");
        RemoveButton.setEnabled(false);
        RemoveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RemoveButtonActionPerformed(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(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(26, 26, 26)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(jLabel4)
                                            .addComponent(jLabel3))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(YComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(XComboBox, 0, 85, Short.MAX_VALUE)))
                                    .addComponent(AddButton)))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(jLabel2))))
                    .addComponent(jLabel1)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(RemoveButton)))
                .addGap(90, 90, 90))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(XComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addGap(13, 13, 13)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(YComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(AddButton))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(15, 15, 15)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(RemoveButton))
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Significance"));

        jLabel6.setText("Significance level:");

        SigTextField.setText("0.05");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(SigTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(154, 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(jLabel6)
                    .addComponent(SigTextField, 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(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(96, Short.MAX_VALUE)
                .addComponent(OKButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(CancelButton)
                .addGap(129, 129, 129))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 346, Short.MAX_VALUE))
                    .addContainerGap(13, 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(338, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(CancelButton, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(OKButton, javax.swing.GroupLayout.Alignment.TRAILING))
                .addGap(27, 27, 27))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(65, Short.MAX_VALUE)))
        );

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

    private void SeriesListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_SeriesListValueChanged
        if (SeriesList.getSelectedIndex() != -1)
            RemoveButton.setEnabled(true);
        else
            RemoveButton.setEnabled(false);
}//GEN-LAST:event_SeriesListValueChanged

    private void XComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_XComboBoxItemStateChanged
        if (XComboBox.getSelectedIndex() == 0 || YComboBox.getSelectedIndex() == 0)
            AddButton.setEnabled(false);
        else {
            AddButton.setEnabled(true);
            AddButton.requestFocusInWindow();
        }
}//GEN-LAST:event_XComboBoxItemStateChanged

    private void YComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_YComboBoxItemStateChanged
        if (XComboBox.getSelectedIndex() == 0 || YComboBox.getSelectedIndex() == 0)
            AddButton.setEnabled(false);
        else {
            AddButton.setEnabled(true);
            AddButton.requestFocusInWindow();
        }
}//GEN-LAST:event_YComboBoxItemStateChanged

    private void AddButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddButtonActionPerformed
        // add selected series to list
        if (XComboBox.getSelectedIndex() == 0) {
            app.showErrorDialog("Select variable 1 of the new series.");
            return;
        }
        if (YComboBox.getSelectedIndex() == 0) {
            app.showErrorDialog("Select variable 2 of the new series.");
            return;
        }
        String x = XComboBox.getSelectedItem().toString();
        String y = YComboBox.getSelectedItem().toString();
        ((DefaultListModel)SeriesList.getModel()).addElement(x.trim()+","+y.trim());
}//GEN-LAST:event_AddButtonActionPerformed

    private void RemoveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RemoveButtonActionPerformed
        // remove selected series from list
        if (SeriesList.getSelectedValue() != null) {
            ((DefaultListModel)SeriesList.getModel()).removeElementAt(
                    SeriesList.getSelectedIndex());
        }
}//GEN-LAST:event_RemoveButtonActionPerformed

    private void OKButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OKButtonActionPerformed
        app.compoundEdit = new DialogEdit("rank correlation");

        double significance = 0;
        String heading = "Spearman's Rank Correlation:";
        String text = "";

        if (SeriesList.getModel().getSize() == 0) {
            app.showErrorDialog("Add at least one series.");
            return;
        }

        // get confidence level from dialog
        try {
            significance = Double.parseDouble(SigTextField.getText());
        } catch (NumberFormatException e) {
            app.showErrorDialog("Enter a number between 0 and 1 for the confidence level.");
            return;
        }
        if (significance <= 0 || significance >= 1) {
            app.showErrorDialog("Enter a number between 0 and 1 for the confidence level.");
            return;
        }
        heading += "  Significance level = " + significance;

        for (int i = 0; i < SeriesList.getModel().getSize(); ++i) {
            String xy = (String) SeriesList.getModel().getElementAt(i);
            text += "--------------------------<br>";
            text += "Series: " + xy + "<br>";
            String[] items = xy.split(",");
            int selectedXColumn = ParentSpreadsheet.parseColumnNumber(items[0]);
            int selectedYColumn = ParentSpreadsheet.parseColumnNumber(items[1]);

            Vector<Cell> StrColumnVector = ParentSpreadsheet.getColumn(selectedXColumn);
            // get x input column of doubles
            Vector<Double> XColumnVector =
                    HelperFunctions.ConvertInputVectorToDoubles(StrColumnVector);

            if (XColumnVector == null) {
                app.showErrorDialog("Invalid input column " + items[0] +
                        ": all data must be numbers.");
                return;
            }
            XColumnVector = HelperFunctions.removeNullValues(XColumnVector);

            StrColumnVector = ParentSpreadsheet.getColumn(selectedYColumn);
            // get x input column of doubles
            Vector<Double> YColumnVector =
                    HelperFunctions.ConvertInputVectorToDoubles(StrColumnVector);

            if (YColumnVector == null) {
                app.showErrorDialog("Invalid input column " + items[1] +
                        ": all data must be numbers.");
                return;
            }
            YColumnVector = HelperFunctions.removeNullValues(YColumnVector);

            if (XColumnVector.size() != YColumnVector.size()) {
                app.showErrorDialog("The number of x values must be the " +
                        "same as the number of y values.");
                return;
            }

            // compute rank correlation
            RankCorrelation CG = new RankCorrelation(
                    XColumnVector, YColumnVector, significance);
            text += CG;

        }

        app.addLogParagraph(heading, 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 AddButton;
    private javax.swing.JButton CancelButton;
    private javax.swing.JButton OKButton;
    private javax.swing.JButton RemoveButton;
    private javax.swing.JList SeriesList;
    private javax.swing.JTextField SigTextField;
    private javax.swing.JComboBox XComboBox;
    private javax.swing.JComboBox YComboBox;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables

}
