/*
 * CIMatchedPairsDialog.java
 *
 * Created on June 11, 2008, 3:49 PM
 */

package org.statcato.dialogs.stat.ci;

import org.statcato.*;
import org.statcato.spreadsheet.*;
import org.statcato.statistics.inferential.*;
import org.statcato.utils.HelperFunctions;
import java.util.*;
import javax.swing.*;
import org.statcato.statistics.BasicStatistics;

/**
 * A dialog for creating confidence intervals for matched pairs, 
 * given the confidence level.
 * Allows the user to specify the data values in the Datasheet or provide
 * summary data.
 * 
 * @author  Margaret Yau
 * @version %I%, %G%
 * @see org.statcato.statistics.inferential.CIMatchedPairs
 * @since 1.0
 */
public class CIMatchedPairsDialog extends StatcatoDialog {

    /** Creates new form CIMatchedPairsDialog */
    public CIMatchedPairsDialog(java.awt.Frame parent, boolean modal,
            Statcato mTab) {
        super(parent, modal);
        initComponents();
        
        app = mTab;
        ParentSpreadsheet = app.getSpreadsheet(); 
        
        ButtonGroup group1 = new ButtonGroup();
        group1.add(SampleRadioButton);
        group1.add(SummaryRadioButton);        
        
        ParentSpreadsheet.populateComboBox(Sample1ComboBox);
        ParentSpreadsheet.populateComboBox(Sample2ComboBox);
        
        getRootPane().setDefaultButton(OKButton);
        setHelpFile("stat-ci-matched");

        name = "Confidence Interval: Matched Pairs";
        description = "For computing confidence intervals for the mean of the " +
                "differences between matched pairs.";
        helpStrings.add("The sample data can be inputted in one of two ways...");
        helpStrings.add("Samples in columns: The sample matched pairs " +
                "are provided in two columns, and the two values in a " +
                "matched pair are provided in the same row.");
        helpStrings.add("Summarized Sample Data: The sample size, mean, " +
                "and standard deviation are provided " +
                "(instead of individual sample values).");
        helpStrings.add("The confidence level must be between 0 and 1.");
    }

    /**
     * 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(Sample1ComboBox);
        updateComboBox(Sample2ComboBox);  
    }
    
    /** 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();
        jPanel1 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        SummaryRadioButton = new javax.swing.JRadioButton();
        jLabel4 = new javax.swing.JLabel();
        Sample1ComboBox = new javax.swing.JComboBox();
        Sample2ComboBox = new javax.swing.JComboBox();
        SizeTextField = new javax.swing.JTextField();
        SampleRadioButton = new javax.swing.JRadioButton();
        jLabel2 = new javax.swing.JLabel();
        MeanTextField = new javax.swing.JTextField();
        StdevTextField = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        ConfidenceTextField = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Confidence Interval: Matched Pairs");

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

        jLabel3.setText("Sample Size:");

        jLabel5.setText("Standard Deviation:");

        jLabel1.setText("First Sample:");

        SummaryRadioButton.setText("Summarized Sample Data");
        SummaryRadioButton.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                SummaryRadioButtonStateChanged(evt);
            }
        });

        jLabel4.setText("Mean:");

        SizeTextField.setEnabled(false);

        SampleRadioButton.setSelected(true);
        SampleRadioButton.setText("Samples in Columns");
        SampleRadioButton.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                SampleRadioButtonStateChanged(evt);
            }
        });

        jLabel2.setText("Second Sample:");

        MeanTextField.setEnabled(false);

        StdevTextField.setEnabled(false);

        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(SummaryRadioButton)
                    .addComponent(SampleRadioButton)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(38, 38, 38)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel5)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(StdevTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 76, Short.MAX_VALUE)
                                    .addComponent(MeanTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                                    .addComponent(SizeTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel1))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(Sample2ComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(Sample1ComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                .addContainerGap(70, Short.MAX_VALUE))
        );

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

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {MeanTextField, SizeTextField, StdevTextField});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(SampleRadioButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(Sample1ComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(Sample2ComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(SummaryRadioButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(SizeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(MeanTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(StdevTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

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

        jLabel6.setText("Confidence level:");

        ConfidenceTextField.setText("0.95");

        jLabel7.setText("0 - 1.00 (e.g. 0.95)");

        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(ConfidenceTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(10, 10, 10)
                .addComponent(jLabel7)
                .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(ConfidenceTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .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()
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(85, 85, 85)
                        .addComponent(OKButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .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()
                .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)
                .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 OKButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OKButtonActionPerformed
        app.compoundEdit = new DialogEdit("CI matched pairs");
        
        int n = 0;
        double s = 0, mean = 0, confidenceLevel;
        
        String heading = "Confidence Interval - Matched Pairs:";
        String text = "";
        
        // get confidence level from dialog
        try {
            confidenceLevel = Double.parseDouble(ConfidenceTextField.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;
        }

        heading += "  confidence level = " + confidenceLevel;
        String columnLabel1 = "", columnLabel2 = "";
        
        // samples of matched pairs provided
        if (SampleRadioButton.isSelected()) {   
            // get data for first sample input column
            columnLabel1 = Sample1ComboBox.getSelectedItem().toString();
            Vector<Double> ColumnVector1 = new Vector<Double>();
            Vector<Double> ColumnVector2 = new Vector<Double>();
            
            if (columnLabel1.equals("")) { // no input variable
                app.showErrorDialog("Select sample 1 input column.");
                return;
            }
            int column = ParentSpreadsheet.parseColumnNumber(columnLabel1);
            Vector<Cell> StrColumnVector = ParentSpreadsheet.getColumn(column);
            ColumnVector1 = HelperFunctions.ConvertInputVectorToDoubles(StrColumnVector);
            if (ColumnVector1 == null) {
                app.showErrorDialog("Invalid input column " + columnLabel1 +
                        ": all data must be numbers.");
                return;
            }
            text += "Sample 1: " + columnLabel1 + "<br>";
            
            columnLabel2 = Sample2ComboBox.getSelectedItem().toString();
            if (columnLabel2.equals("")) { // no input variable
                app.showErrorDialog("Select sample 2 input column.");
                return;
            }
            column = ParentSpreadsheet.parseColumnNumber(columnLabel2);
            StrColumnVector = ParentSpreadsheet.getColumn(column);
            ColumnVector2 = HelperFunctions.ConvertInputVectorToDoubles(StrColumnVector);
            if (ColumnVector2 == null) {
                app.showErrorDialog("Invalid input column " + columnLabel2 +
                        ": all data must be numbers.");
                return;
            }
            text += "Sample 2: " + columnLabel2 + "<br>";
            
            Vector<Double> DiffVector = HelperFunctions.ComputeDiffVector(
                    ColumnVector1, ColumnVector2);
            if (DiffVector == null) {
                app.showErrorDialog("There are unmatched pairs in the sample.");
                return;
            }
            
            n = BasicStatistics.Nnonmissing(DiffVector);
            mean = BasicStatistics.mean(DiffVector).doubleValue();
            s = BasicStatistics.stdev(DiffVector).doubleValue();            
        }
        // summary sample data provided
        else {
            try {
                n = Integer.parseInt(SizeTextField.getText());
                if (n < 1) 
                    throw new NumberFormatException();
                mean = Double.parseDouble(MeanTextField.getText()); 
                s = Double.parseDouble(StdevTextField.getText());
            } catch (NumberFormatException e) {
                app.showErrorDialog("Invalid summary data.");
                return;
            }
            text += "Input: Summary data" + "<br>";
        }
        
        ConfidenceInterval CI = new CIMatchedPairs(confidenceLevel, n, mean, s);
        
        text += "Difference of Matched Pairs " + columnLabel1 + " - " + 
                columnLabel2 + "<br>";
        text += "<br><table border='1'>";
        text += "<tr><td>N</td><td>Mean</td><td>Stdev</td><td>Margin of Error</td><td>";
        text += HelperFunctions.formatFloat(confidenceLevel * 100, 2) + "%CI</td></tr>";
        text += "<tr><td>" + n + "</td><td>" +
                HelperFunctions.formatFloat(mean, 3) + "</td><td>" + 
                HelperFunctions.formatFloat(s, 3) +
                "</td><td>" + HelperFunctions.formatFloat(CI.marginOfError(), 3) 
                + "</td><td>" + CI.toString() + "</td></tr></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 SampleRadioButtonStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_SampleRadioButtonStateChanged
        if (SampleRadioButton.isSelected()) {
            Sample1ComboBox.setEnabled(true);
            Sample2ComboBox.setEnabled(true);
        }
        else {
            Sample1ComboBox.setEnabled(false);
            Sample2ComboBox.setEnabled(false);
        }    
    }//GEN-LAST:event_SampleRadioButtonStateChanged

    private void SummaryRadioButtonStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_SummaryRadioButtonStateChanged
        if (SummaryRadioButton.isSelected()) {
            SizeTextField.setEnabled(true);
            MeanTextField.setEnabled(true);
            StdevTextField.setEnabled(true);
        }
        else {
            SizeTextField.setEnabled(false);
            MeanTextField.setEnabled(false);
            StdevTextField.setEnabled(false);
        }
    }//GEN-LAST:event_SummaryRadioButtonStateChanged

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton CancelButton;
    private javax.swing.JTextField ConfidenceTextField;
    private javax.swing.JTextField MeanTextField;
    private javax.swing.JButton OKButton;
    private javax.swing.JComboBox Sample1ComboBox;
    private javax.swing.JComboBox Sample2ComboBox;
    private javax.swing.JRadioButton SampleRadioButton;
    private javax.swing.JTextField SizeTextField;
    private javax.swing.JTextField StdevTextField;
    private javax.swing.JRadioButton SummaryRadioButton;
    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.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    // End of variables declaration//GEN-END:variables
    
}
