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

/*
 * KruskalWallisDialog.java
 *
 * Created on Jan 25, 2010, 10:59:14 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.KruskalWallisTest;

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

/**
 * A dialog for the Kruskal-Wallis Test
 *
 * @author  Margaret Yau
 * @version %I%, %G%
 * @see org.statcato.statistics.inferential.nonparametrics.KruskalWallisTest
 * @since 1.0
 */
public class KruskalWallisDialog extends StatcatoDialog {

    /** Creates new form KruskalWallisDialog */
    public KruskalWallisDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        app = (Statcato)parent;
        ParentSpreadsheet = app.getSpreadsheet();

        customInitComponents();

        setHelpFile("stat-nonparam-kruskal-wallis");
        name = "Kruskal-Wallis Test";
        description = "For performing the Kruskal-Wallis Test for "
                + "samples from three or more independent populations.";
        helpStrings.add("Provide sample values for different populations in " +
                "separate columns and add the columns to the list of responses.");
        helpStrings.add("Provide the significance level.");
    }

    private void customInitComponents() {
        ParentSpreadsheet.populateMutableColumnsList(ColList);
        ColList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        VarList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        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() {
        // update column list
        clearMutableColumnsList(ColList);
        clearMutableColumnsList(VarList);
        ParentSpreadsheet.populateMutableColumnsList(ColList);
    }

    /** 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() {

        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();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        VarList = new JList(new DefaultListModel());
        RemoveButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        ColList = new JList(new DefaultListModel());
        jLabel1 = new javax.swing.JLabel();
        AddButton = new javax.swing.JButton();
        ClearButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Kruskal-Wallis Test");

        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())
        );
        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);
            }
        });

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

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

        RemoveButton.setText("Remove from list >>");
        RemoveButton.setEnabled(false);
        RemoveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RemoveButtonActionPerformed(evt);
            }
        });

        jLabel2.setText("<html>Select the column to be <br>included in the analysis:");

        ColList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                ColListValueChanged(evt);
            }
        });
        jScrollPane2.setViewportView(ColList);

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

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

        ClearButton.setText("Clear Input List");
        ClearButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ClearButtonActionPerformed(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)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(AddButton)
                            .addComponent(RemoveButton)))
                    .addComponent(jLabel1)
                    .addComponent(ClearButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {AddButton, RemoveButton});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1))
                    .addComponent(jLabel2))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(44, 44, 44)
                        .addComponent(AddButton)
                        .addGap(31, 31, 31)
                        .addComponent(RemoveButton)
                        .addGap(36, 36, 36))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE)
                        .addContainerGap())))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addComponent(jScrollPane1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(ClearButton)
                .addGap(11, 11, 11))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 414, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(OKButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(CancelButton))
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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

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

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

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

        String heading = "Kruskal-Wallis Test:";
        String text = "";
        Vector<Vector<Double>> vectors = new Vector<Vector<Double>>();
        double significance = 0;

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

        if (VarList.getModel().getSize() < 3) {
            app.showErrorDialog("Select at least three columns " +
                    "to include in the analysis.");
            return;
        }

        Vector<Cell> StrColumnVector;

        text += "Selected column variables:  ";

        for (int i = 0; i < VarList.getModel().getSize(); ++i) {
            String x = (String) VarList.getModel().getElementAt(i);
            int selectedXColumn = ParentSpreadsheet.parseColumnNumber(x);

            StrColumnVector = ParentSpreadsheet.getColumn(selectedXColumn);
            // get x input column of doubles
            Vector<Double> XColumnVector =
                    HelperFunctions.ConvertInputVectorToDoubles(StrColumnVector);
            if (XColumnVector == null) {
                app.showErrorDialog("Invalid input column " + x +
                        ": all data must be numbers.");
                return;
            }

            XColumnVector = HelperFunctions.removeNullValues(XColumnVector);
            if (XColumnVector.size() == 0) {
                app.showErrorDialog("Invalid input column " + x +
                        ": empty column.");
            }
            vectors.addElement(XColumnVector);
            text += x + "  ";
        }
        text += "<br><br>";

        KruskalWallisTest kw = new KruskalWallisTest(vectors, significance);

        text += kw;

        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

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

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

    private void ColListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_ColListValueChanged
        if (ColList.getSelectedIndex() != -1) {
            AddButton.setEnabled(true);
            AddButton.requestFocusInWindow();
        }
        else
            AddButton.setEnabled(false);
}//GEN-LAST:event_ColListValueChanged

    private void AddButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddButtonActionPerformed
        // add selected series to list
        if (ColList.getSelectedIndex() == -1) {
            app.showErrorDialog("Select the column to be included.");
            return;
        }

        String x = ColList.getSelectedValue().toString();

        ((DefaultListModel)VarList.getModel()).addElement(x);
        ((DefaultListModel)ColList.getModel()).removeElementAt(ColList.getSelectedIndex());
}//GEN-LAST:event_AddButtonActionPerformed

    private void ClearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ClearButtonActionPerformed
        clearMutableColumnsList(ColList);
        clearMutableColumnsList(VarList);
        ParentSpreadsheet.populateMutableColumnsList(ColList);
}//GEN-LAST:event_ClearButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AddButton;
    private javax.swing.JButton CancelButton;
    private javax.swing.JButton ClearButton;
    private javax.swing.JList ColList;
    private javax.swing.JButton OKButton;
    private javax.swing.JButton RemoveButton;
    private javax.swing.JTextField SigTextField;
    private javax.swing.JList VarList;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables

}
