/*
 * CI1PopVarDialog.java
 *
 * Created on May 22, 2008, 4:27 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 one population variance, 
 * given the confidence level.
 * Allows the user to specify the data values in a column or provide
 * summary data.
 * 
 * @author  Margaret Yau
 * @version %I%, %G%
 * @see org.statcato.statistics.inferential.CIOnePopVar
 * @since 1.0
 */
public class CI1PopVarDialog extends StatcatoDialog {

    /** Creates new form CI1PopVarDialog */
    public CI1PopVarDialog(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);
        
        ButtonGroup group2 = new ButtonGroup();
        group2.add(VarRadioButton);
        group2.add(StdevRadioButton);
        
        ParentSpreadsheet.populateComboBox(ColumnComboBox);
        
        getRootPane().setDefaultButton(OKButton);    
        setHelpFile("stat-ci-1var");
        name = "Confidence Interval: One Population Variance";
        description = "For computing the confidence intervals for a " +
                "population variance in one population.";
        helpStrings.add("To provde sample data in a column, " +
                "select the Samples in column: radio button, " +
                "and select the column name in the given drop-down menu.");
        helpStrings.add("If individual sample data is not available, " +
                "select the Summarized sample data radio button. " +
                "Enter sample size and either sample variance or " +
                "sample standard deviation in the provided text boxes.");
        helpStrings.add("Enter the confidence level (between 0 and 1) in the " +
                "Confidence level: text box.");
    }

    /**
     * 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(ColumnComboBox);      
    }
    
    /** 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();
        jLabel2 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        ColumnComboBox = new javax.swing.JComboBox();
        SummaryRadioButton = new javax.swing.JRadioButton();
        SampleRadioButton = new javax.swing.JRadioButton();
        SampleStdevTextField = new javax.swing.JTextField();
        SampleSizeTextField = new javax.swing.JTextField();
        SampleSizeLabel = new javax.swing.JLabel();
        StdevRadioButton = new javax.swing.JRadioButton();
        SampleVarTextField = new javax.swing.JTextField();
        VarRadioButton = new javax.swing.JRadioButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        ConfidenceTextField = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("1-Population Variance");

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

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

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

        SampleStdevTextField.setEnabled(false);

        SampleSizeTextField.setEnabled(false);

        SampleSizeLabel.setText("Sample Size:");
        SampleSizeLabel.setEnabled(false);

        StdevRadioButton.setText("Standard deviation:");
        StdevRadioButton.setEnabled(false);
        StdevRadioButton.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                StdevRadioButtonStateChanged(evt);
            }
        });

        SampleVarTextField.setEnabled(false);

        VarRadioButton.setSelected(true);
        VarRadioButton.setText("Variance:");
        VarRadioButton.setEnabled(false);
        VarRadioButton.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                VarRadioButtonStateChanged(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()
                        .addGap(26, 26, 26)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(SampleSizeLabel)
                            .addComponent(VarRadioButton)
                            .addComponent(StdevRadioButton))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(SampleSizeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(SampleVarTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(SampleStdevTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(SampleRadioButton)
                    .addComponent(SummaryRadioButton)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(ColumnComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(96, 96, 96)))
                .addContainerGap(51, Short.MAX_VALUE))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {SampleSizeTextField, SampleStdevTextField, SampleVarTextField});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(SampleRadioButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ColumnComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(10, 10, 10)
                .addComponent(SummaryRadioButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(SampleSizeLabel)
                    .addComponent(SampleSizeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(14, 14, 14)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(SampleVarTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(VarRadioButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(SampleStdevTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(StdevRadioButton))
                .addContainerGap(19, Short.MAX_VALUE))
        );

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

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

        jLabel6.setText("Confidence level:");

        ConfidenceTextField.setText("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)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addContainerGap(15, 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(ConfidenceTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(jLabel1))
                .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, false)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(44, 44, 44)
                        .addComponent(jLabel2))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(90, 90, 90)
                        .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()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(201, 201, 201)
                        .addComponent(jLabel2))
                    .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)
                .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 SummaryRadioButtonStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_SummaryRadioButtonStateChanged
        if (SummaryRadioButton.isSelected()) {
            SampleSizeLabel.setEnabled(true);
            SampleSizeTextField.setEnabled(true);
            StdevRadioButton.setEnabled(true); 
            VarRadioButton.setEnabled(true);
            if (StdevRadioButton.isSelected()) {
                SampleStdevTextField.setEnabled(true);                               
            }
            else {                
                SampleVarTextField.setEnabled(true);
            }
        } else  {
            SampleSizeLabel.setEnabled(false);
            SampleSizeTextField.setEnabled(false);
            SampleStdevTextField.setEnabled(false);
            SampleVarTextField.setEnabled(false);
            VarRadioButton.setEnabled(false);
            StdevRadioButton.setEnabled(false);
        }
    }//GEN-LAST:event_SummaryRadioButtonStateChanged

    private void SampleRadioButtonStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_SampleRadioButtonStateChanged
        if (SampleRadioButton.isSelected()) {
            ColumnComboBox.setEnabled(true);
        } else {
            ColumnComboBox.setEnabled(false);
        }
    }//GEN-LAST:event_SampleRadioButtonStateChanged

    private void OKButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OKButtonActionPerformed
        app.compoundEdit = new DialogEdit("CI 1 variance");
        
        int n = 0;
        double s = 0, s2 = 0, confidenceLevel;
        Vector<Double> ColumnVector = new Vector<Double>();
        
        String heading = "Confidence Interval - One population variance:";
        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;
     
        // get input
        if (SampleRadioButton.isSelected()) {
            // get data for selected input column
            String columnLabel = ColumnComboBox.getSelectedItem().toString();
            if (columnLabel.equals("")) { // no input variable
                app.showErrorDialog("Select the input column.");
                return;
            }
            int column = ParentSpreadsheet.parseColumnNumber(columnLabel);
            Vector<Cell> StrColumnVector = ParentSpreadsheet.getColumn(column);
            ColumnVector = HelperFunctions.ConvertInputVectorToDoubles(StrColumnVector);
            if (ColumnVector == null) {
                app.showErrorDialog("Invalid input column " + columnLabel +
                        ": all data must be numbers.");
                return;
            }
            text += "Input: " + columnLabel + "<br>";
            n = BasicStatistics.Nnonmissing(ColumnVector);
            s2 = BasicStatistics.variance(ColumnVector).doubleValue();
            s = BasicStatistics.stdev(ColumnVector).doubleValue();
        } else {
            // get summary data
            try {
                n = Integer.parseInt(SampleSizeTextField.getText());
                if (VarRadioButton.isSelected()) {
                    s2 = Double.parseDouble(SampleVarTextField.getText());
                    s = Math.sqrt(s2);
                }
                else {
                    s = Double.parseDouble(SampleStdevTextField.getText());
                    s2 = s * s;
                }              
            } catch (NumberFormatException e) {
                app.showErrorDialog("Invalid summary data.");
                return;
            }
            text += "Input: Summary data" + "<br>";
        }
        
        CIOnePopVar CI = new CIOnePopVar(confidenceLevel, n, s2);
        text += "<br><table border='1'>";
            text += "<tr><td>N</td><td>Variance</td><td>Stdev</td><td>";
            text += HelperFunctions.formatFloat(confidenceLevel * 100, 2) + 
                    "%CI Variance</td><td>" +
                    HelperFunctions.formatFloat(confidenceLevel * 100, 2) +
                    "%CI Stdev</td></tr>";
            text += "<tr><td>" + n + "</td><td>" + 
                HelperFunctions.formatFloat(s2, 3) + "</td><td>" +
                HelperFunctions.formatFloat(s, 3) + "</td><td>" + 
                CI.toString() + "</td><td>" +
                CI.stdevCI() + "</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 VarRadioButtonStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_VarRadioButtonStateChanged
        if (VarRadioButton.isSelected()) {
            SampleVarTextField.setEnabled(true);
            SampleStdevTextField.setEnabled(false);
        }
        else {
            SampleVarTextField.setEnabled(false);
            SampleStdevTextField.setEnabled(true);
        }
    }//GEN-LAST:event_VarRadioButtonStateChanged

    private void StdevRadioButtonStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_StdevRadioButtonStateChanged
        if (StdevRadioButton.isSelected()) {
            SampleVarTextField.setEnabled(false);
            SampleStdevTextField.setEnabled(true);
        }
        else {
            SampleVarTextField.setEnabled(true);
            SampleStdevTextField.setEnabled(false);
        }
    }//GEN-LAST:event_StdevRadioButtonStateChanged

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton CancelButton;
    private javax.swing.JComboBox ColumnComboBox;
    private javax.swing.JTextField ConfidenceTextField;
    private javax.swing.JButton OKButton;
    private javax.swing.JRadioButton SampleRadioButton;
    private javax.swing.JLabel SampleSizeLabel;
    private javax.swing.JTextField SampleSizeTextField;
    private javax.swing.JTextField SampleStdevTextField;
    private javax.swing.JTextField SampleVarTextField;
    private javax.swing.JRadioButton StdevRadioButton;
    private javax.swing.JRadioButton SummaryRadioButton;
    private javax.swing.JRadioButton VarRadioButton;
    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;
    // End of variables declaration//GEN-END:variables
    
}
