/*
 * CI1PopPropDialog.java
 *
 * Created on May 21, 2008, 2:28 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.*;

/**
 * A dialog for creating confidence intervals for one population proportion, 
 * 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.CIOnePopProp
 * @since 1.0
 */
public class CI1PopPropDialog extends StatcatoDialog {

    /** Creates new form CI1PopPropDialog */
    public CI1PopPropDialog(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(ColumnComboBox);
        
        getRootPane().setDefaultButton(OKButton);      
        setHelpFile("stat-ci-1prop");
        name = "Confidence Interval: One Population Proportion";
        description = "For computing the confidence intervals for a population " +
                "proportion in one population using normal approximation. ";
        helpStrings.add("If you provide sample data, put sample values of " +
                "at most two categories in a column in the datasheet. " +
                "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 the number of trials and the number of events " +
                "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();
        jPanel1 = new javax.swing.JPanel();
        ColumnComboBox = new javax.swing.JComboBox();
        TrialsTextField = new javax.swing.JTextField();
        SampleRadioButton = new javax.swing.JRadioButton();
        TrialsLabel = new javax.swing.JLabel();
        SummaryRadioButton = new javax.swing.JRadioButton();
        EventsLabel = new javax.swing.JLabel();
        EventsTextField = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        ConfidenceTextField = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Confidence Interval: One Population Proportion");

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

        TrialsTextField.setEnabled(false);

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

        TrialsLabel.setText("Number of trials:");
        TrialsLabel.setEnabled(false);

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

        EventsLabel.setText("Number of events:");
        EventsLabel.setEnabled(false);

        EventsTextField.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)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(9, 9, 9)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(EventsLabel)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(3, 3, 3)
                                .addComponent(TrialsLabel)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(TrialsTextField)
                            .addComponent(EventsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(SummaryRadioButton)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(ColumnComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(SampleRadioButton)))
                .addContainerGap(77, Short.MAX_VALUE))
        );
        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(EventsLabel)
                    .addComponent(EventsTextField, 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(TrialsLabel)
                    .addComponent(TrialsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

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

        ConfidenceTextField.setText("0.95");

        jLabel6.setText("Confidence level:");

        jLabel1.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)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addContainerGap(16, 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(jLabel1)
                    .addComponent(jLabel6))
                .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.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, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(91, 91, 91)
                        .addComponent(OKButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(CancelButton)))
                .addContainerGap(10, 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()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .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))
                .addGap(20, 20, 20))
        );

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

    private void OKButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OKButtonActionPerformed
        app.compoundEdit = new DialogEdit("CI 1 proportion");
        
        int events = 0, trials = 0;
        double confidenceLevel;
        
        String heading = "Confidence Interval - One population proportion:";
        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);
            
            String cat1 = "", cat2 = "";    // two categories
            int count1 = 0, count2 = 0;     // number of events in each category
            
            // find out the two categories present in the column
            // error if more than two categories
            for (int i = 0; i < StrColumnVector.size(); ++i) {
                String s = StrColumnVector.elementAt(i).getContents().trim();
                if (!s.equals("")) {
                    if (cat1.equals("")) {  // first instance of category 1
                        cat1 = s;
                        count1++;
                    } 
                    else if (s.equals(cat1)) { // non-first instance of category 1
                        count1++;
                    }     
                    else if (cat2.equals("")) { // first instance of category 2
                        cat2 = s;
                        count2++;
                    }
                    else if (s.equals(cat2)) { // non-first instance of category 2
                        count2++;
                    }
                    else { // neither category 1 or 2
                        app.showErrorDialog("The input column contains more than two categories.");
                        return;
                    }
                }
            }
            
            trials = count1 + count2;
            if (trials == 0) {  // empty column
                app.showErrorDialog("The input column is empty.");
                return;
            }
            events = count1;
            text += "Input: " + columnLabel + "<br>";
            text += "Event: " + cat1 + "<br>";            
        } else {
            // get summary data
            try {
                events = Integer.parseInt(EventsTextField.getText());
                trials = Integer.parseInt(TrialsTextField.getText());
            } catch (NumberFormatException e) {
                app.showErrorDialog("Invalid summary data.");
                return;
            }
            if (events > trials) {
                app.showErrorDialog("The number of events must not be" +
                        " greater than the number of trials.");
                return;
            }
            text += "Input: Summary data" + "<br>";
        }
        
        double p = (double)events / trials;
        
        if (trials * p < 5 || trials * (1-p) < 5)
            text += "WARNING: The sample size is too small for normal approximation" 
                    + " to be valid.<br>";
        
        ConfidenceInterval CI;
        CI = new CIOnePopProp(confidenceLevel, trials, p, CIOnePopProp.NORMAL);
        
        text += "<br><table border='1'>";
        text += "<tr><td>Number of trials</td><td>Number of Events</td>" +
                "<td>Sample proportion</td><td>Margin of Error</td><td>" + 
                HelperFunctions.formatFloat(confidenceLevel * 100, 2) + "%CI</td></tr>";
        text += "<tr><td>" + trials + "</td><td>" + events + "</td><td>" +
                HelperFunctions.formatFloat(p, 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()) {
            ColumnComboBox.setEnabled(true);
        } else {
            ColumnComboBox.setEnabled(false);
        }
    }//GEN-LAST:event_SampleRadioButtonStateChanged

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

    // 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.JLabel EventsLabel;
    private javax.swing.JTextField EventsTextField;
    private javax.swing.JButton OKButton;
    private javax.swing.JRadioButton SampleRadioButton;
    private javax.swing.JRadioButton SummaryRadioButton;
    private javax.swing.JLabel TrialsLabel;
    private javax.swing.JTextField TrialsTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    // End of variables declaration//GEN-END:variables
    
}
