/*
 * ContingencyTableDialog.java
 *
 * Created on July 7, 2008, 11:24 AM
 */

package org.statcato.dialogs.stat.multinomial;

import org.statcato.*;
import org.statcato.spreadsheet.*;
import org.statcato.utils.HelperFunctions;
import javax.swing.*;
import java.util.*;
import org.statcato.statistics.inferential.*;
        
/**
 * A dialog for a chi-square contingency table test given a significance level.  
 * Allows the user to specify the columns of a contingency table.  
 * Computes degrees of freedom, critical value, 
 * test statistic, and 
 * p-Value and displays the results in the log window.
 * 
 * @author  Margaret Yau
 * @version %I%, %G%
 * @see org.statcato.statistics.inferential.ContingencyTable
 * @since 1.0
 */
public class ContingencyTableDialog extends StatcatoDialog {

    /** Creates new form ContingencyTableDialog */
    public ContingencyTableDialog(java.awt.Frame parent, boolean modal,
            Statcato app) {
        super(parent, modal);
        this.app = app;
        ParentSpreadsheet = app.getSpreadsheet(); 
      
        initComponents();
        customInitComponents();    
        setHelpFile("stat-multi-contingency_table");
        name = "Chi-Square Test: Contingency Table";
        description = "For testing independence in a contingency table.";
        helpStrings.add("The columns of a contingency table should be placed " +
                "in separate columns in the Datasheet. All the columns in a " +
                "contingency table must have the same number of rows.");
        helpStrings.add("To specify a column of a contingency table, " +
                "select the column in the Select a column of the table: " +
                "drop-down menu, and click the Add Column button. ");
        helpStrings.add("Specify the significance level.");
    }

    /**
     * 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() {
        clearMutableColumnsList(ColList);
        clearMutableColumnsList(VarList);
        ParentSpreadsheet.populateMutableColumnsList(ColList);
    }
    
    public void customInitComponents() {        
        ParentSpreadsheet.populateMutableColumnsList(ColList);
        ColList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        VarList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        getRootPane().setDefaultButton(OKButton);
    }
    
    /** 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() {

        OKButton = new javax.swing.JButton();
        CancelButton = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        SigTextField = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        VarList = new JList(new DefaultListModel());
        RemoveButton1 = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        ColList = new JList(new DefaultListModel());
        jLabel1 = new javax.swing.JLabel();
        AddButton1 = new javax.swing.JButton();
        ClearButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Chi-Square Test: Contingency Table");

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

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

        jLabel6.setText("Significance level:");

        SigTextField.setText("0.05");

        jLabel4.setText("0 - 1.00 (e.g. 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)
                .addGap(10, 10, 10)
                .addComponent(jLabel4)
                .addContainerGap(159, 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)
                    .addComponent(jLabel4))
                .addContainerGap())
        );

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

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

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

        jLabel5.setText("Select a column of the table:");

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

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

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

        ClearButton1.setText("Clear Input List");
        ClearButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ClearButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(22, 22, 22)
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(AddButton1)
                                    .addComponent(RemoveButton1)))
                            .addComponent(jLabel1))
                        .addGap(28, 28, 28)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(ClearButton1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {AddButton1, RemoveButton1});

        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel5))
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(46, 46, 46)
                        .addComponent(AddButton1)
                        .addGap(18, 18, 18)
                        .addComponent(RemoveButton1))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 122, Short.MAX_VALUE)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 122, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(ClearButton1)))
                .addContainerGap())
        );

        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.LEADING)
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(159, 159, 159)
                        .addComponent(OKButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(CancelButton)))
                .addContainerGap())
        );

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

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, 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)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(OKButton)
                    .addComponent(CancelButton))
                .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("contingency table");
        
        Vector<Vector<Double>> table = new Vector<Vector<Double>>();
        int numRows = -1;
        double confidenceLevel = 0;
        
        String heading = "Chi-Square Test: Contingency Table:";
        String text = "";
        
        // get confidence level from dialog
        try {
            confidenceLevel = 1 - Double.parseDouble(SigTextField.getText());
        } catch (NumberFormatException e) {
            app.showErrorDialog("Enter a number between 0 and 1 for the confidence level.");
            return;
        }
        if (confidenceLevel <= 0 || confidenceLevel >= 1) {
            app.showErrorDialog("Enter a number between 0 and 1 for the confidence level.");
            return;
        }
     
        String header = "";
        
        if (VarList.getModel().getSize() == 0) {
            app.showErrorDialog("The list of columns is empty.  " +
                    "Select at least one column.");
            return;
        }
        for (int i = 0; i < VarList.getModel().getSize(); ++i) {
            String x = (String) VarList.getModel().getElementAt(i);
            header += "<th>" + x + "</th>";
            int selectedXColumn = ParentSpreadsheet.parseColumnNumber(x);
            
            Vector<Cell> StrColumnVector = ParentSpreadsheet.getColumn(
                    selectedXColumn);
            // get x input column of doubles
            Vector<Double> ColumnVector =
                    HelperFunctions.ConvertInputVectorToDoubles(StrColumnVector);
            ColumnVector = HelperFunctions.removeNullValues(ColumnVector);
            
            if (ColumnVector == null) {
                app.showErrorDialog("Invalid input column " + x +
                        ": all data must be numbers.");
                return;
            }
            
            if (numRows == -1)
                numRows = ColumnVector.size();
            else {
                if (numRows != ColumnVector.size()) {
                    app.showErrorDialog("All columns must have the same " +
                            "number of elements.");
                    return;
                }
            }           
            table.addElement(ColumnVector);
        }
        
        ContingencyTable CT = new ContingencyTable(table);
        text += "<table border=1><tr align='right'><th>&nbsp;</th>" + header;
        text += "<th>Total</th></tr>";
        text += CT.toString() + "</table><br>";
        text += "(expected frequency), [test statistic contribution]<br><br>";
        text += "<table border=1>";
        text += "<tr><td>Significance Level</td><td>DOF</td>" +
                "<td>&Chi;<sup>2</sup></td><td>Critical value</td>" +
                "<td>p-Value</td></tr>";
        text += "<tr><td>" + HelperFunctions.formatFloat(1 - confidenceLevel, 2)
                + "</td><td>" + CT.DOF() + "</td><td>" + 
                HelperFunctions.formatFloat(CT.testStatistics(), 4) 
                + "</td><td>" + 
                HelperFunctions.formatFloat(CT.criticalValue(confidenceLevel), 4)
                + "</td><td>" + 
                HelperFunctions.formatFloat(CT.pValue(), 4) + "</td></tr>";
        text += "</table>";
        
        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)
            RemoveButton1.setEnabled(true);
        else
            RemoveButton1.setEnabled(false);
}//GEN-LAST:event_VarListValueChanged

    private void RemoveButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RemoveButton1ActionPerformed
        // 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_RemoveButton1ActionPerformed

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

    private void AddButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddButton1ActionPerformed
        // 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_AddButton1ActionPerformed

    private void ClearButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ClearButton1ActionPerformed
        clearMutableColumnsList(ColList);
        clearMutableColumnsList(VarList);
        ParentSpreadsheet.populateMutableColumnsList(ColList);
}//GEN-LAST:event_ClearButton1ActionPerformed
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AddButton1;
    private javax.swing.JButton CancelButton;
    private javax.swing.JButton ClearButton1;
    private javax.swing.JList ColList;
    private javax.swing.JButton OKButton;
    private javax.swing.JButton RemoveButton1;
    private javax.swing.JTextField SigTextField;
    private javax.swing.JList VarList;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    // End of variables declaration//GEN-END:variables
    
}
