/*
 * StandardizeDialog.java
 *
 * Created on April 10, 2008, 2:50 PM
 */

package org.statcato.dialogs.data;

import org.statcato.*;
import org.statcato.spreadsheet.*;
import org.statcato.utils.*;
import org.statcato.statistics.*;
import javax.swing.*;
import java.util.Vector;

/**
 * A dialog for standardizing data values. Three ways of standardization
 * are available: (1) subtract the mean and divide by the standard deviation of the 
 * data values, (2) subtract a specified number and divide by another number,
 * (3) make the numbers fit in a specified range. 
 * 
 * @author  Margaret Yau
 * @version %I%, %G%
 * @since 1.0
 */
public class StandardizeDialog extends StatcatoDialog {

    /** Creates new form StandardizeDialog */
    public StandardizeDialog(java.awt.Frame parent, boolean modal, Statcato app) {
        super(parent, modal);
        this.ParentSpreadsheet = app.getSpreadsheet();
        this.app = app;
        initComponents();
        
        ButtonGroup group = new ButtonGroup();
        group.add(DefaultRadioButton);
        group.add(SubtractDivideRadioButton);
        group.add(RangeRadioButton);
        
        getRootPane().setDefaultButton(OKButton);
        setHelpFile("data-standardize");
        name = "Standardize";
        description = "For performing data transformation on columns of data, " +
                "including scaling and moving the center of data in a column, " +
                "as well as adjusting the range of the data .";
        helpStrings.add("Enter the names of the input columns and output columns.");
        helpStrings.add("Select the method of standardization.");
    }

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

    }
    
    /** 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();
        jLabel1 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        InputTextField = new javax.swing.JTextField();
        OutputTextField = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        FromTextField = new javax.swing.JTextField();
        DefaultRadioButton = new javax.swing.JRadioButton();
        RangeRadioButton = new javax.swing.JRadioButton();
        jLabel5 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        SubtractTextField = new javax.swing.JTextField();
        ToTextField = new javax.swing.JTextField();
        DivideTextField = new javax.swing.JTextField();
        SubtractDivideRadioButton = new javax.swing.JRadioButton();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Standardize");

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

        jLabel1.setText("Input Column(s):");

        jLabel6.setText("<html>\nThe number of input columns must be the same as <br>the number of columns for storing results.\n</html>");

        jLabel2.setText("Store results in column(s):");

        jLabel8.setText("<html>\nEnter valid column names separated by space.<br>\nFor a continuous range of columns, separate using dash (e.g. C1-C30).<br>\n</html>\n");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(InputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(69, 69, 69)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(OutputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel8))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 356, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(InputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(OutputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, 51, Short.MAX_VALUE))
        );

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

        FromTextField.setEnabled(false);

        DefaultRadioButton.setSelected(true);
        DefaultRadioButton.setText("Subtract mean and divide by standard deviation (z-score)");

        RangeRadioButton.setText("Make range ");
        RangeRadioButton.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                RangeRadioButtonStateChanged(evt);
            }
        });

        jLabel5.setText("To:");

        jLabel4.setText("From:");

        SubtractTextField.setEnabled(false);

        ToTextField.setEnabled(false);

        DivideTextField.setEnabled(false);

        SubtractDivideRadioButton.setText("Subtract");
        SubtractDivideRadioButton.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                SubtractDivideRadioButtonStateChanged(evt);
            }
        });

        jLabel3.setText("Then divide by");

        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()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(RangeRadioButton)
                    .addComponent(SubtractDivideRadioButton)
                    .addComponent(DefaultRadioButton)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(37, 37, 37)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(FromTextField)
                            .addComponent(ToTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(35, 35, 35)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(SubtractTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(DivideTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addComponent(jLabel3)))
                .addContainerGap(78, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(DefaultRadioButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(SubtractDivideRadioButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(SubtractTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(DivideTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(RangeRadioButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(FromTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(ToTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .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(127, 127, 127)
                        .addComponent(OKButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(CancelButton)))
                .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)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .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, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CancelButton)
                    .addComponent(OKButton))
                .addContainerGap())
        );

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

    private void OKButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OKButtonActionPerformed
        app.compoundEdit = new DialogEdit("standardize");
        
        int[] inputColumnNumbers = 
                ParentSpreadsheet.getColumnNumbersArrayFromString(InputTextField.getText());  
        int[] storeColumnNumbers = 
                ParentSpreadsheet.getColumnNumbersArrayFromString(OutputTextField.getText());
        
        if (inputColumnNumbers.length != storeColumnNumbers.length) {
            app.showErrorDialog("The number of input columns must be the same as" +
                    " the number of columns for storing results.");
            return;
        }
        
        Vector<Cell> StrColumnVector;
        String columnLabel;
        Vector<Double> ColumnVector, ResultVector;
        
        String heading = "", text = "";
        
        for (int i = 0; i < inputColumnNumbers.length; ++i) {
            StrColumnVector = ParentSpreadsheet.getColumn(inputColumnNumbers[i]);               
            columnLabel = ParentSpreadsheet.getColumnFullLabel(inputColumnNumbers[i]);
            heading += "Standardize " + columnLabel + " -> " +
                    ParentSpreadsheet.getColumnFullLabel(storeColumnNumbers[i]);
            ColumnVector = HelperFunctions.ConvertInputVectorToDoubles(StrColumnVector);
            if (ColumnVector == null) {
                app.showErrorDialog("Invalid input column " + columnLabel +
                    ": all data must be numbers.");
                return;            
            } 
            
            if (DefaultRadioButton.isSelected()) {
                // subtract mean and divide by standard deviation
                ResultVector = BasicStatistics.standardize(ColumnVector);
                if (ResultVector == null) {
                    app.showErrorDialog("Cannot standardize column " + columnLabel);
                    return;
                }
                ParentSpreadsheet.setColumn(storeColumnNumbers[i], 
                        HelperFunctions.ConvertDoubleVectorToString(ResultVector));
                text += "subtract mean and divide by standard deviation";
            }
            else if (SubtractDivideRadioButton.isSelected()) {
                // subtract by a specific # and then divide by another # 
                try {
                    double num1 = Double.parseDouble(SubtractTextField.getText());
                    double num2 = Double.parseDouble(DivideTextField.getText());
                    if (num2 == 0) {
                        app.showErrorDialog("Cannot divide by 0");
                        return;
                    }
                    ResultVector = BasicStatistics.customStandardize(ColumnVector, 
                            num1, num2);
                    ParentSpreadsheet.setColumn(storeColumnNumbers[i], 
                            HelperFunctions.ConvertDoubleVectorToString(ResultVector));
                    text += "subtract " + num1 + " and divide by "
                            + num2;
                }
                catch (NumberFormatException e) {
                    app.showErrorDialog("Enter valid numbers for subtraction" +
                            " and division.");
                    return;
                }
            }
            else if (RangeRadioButton.isSelected()) {
                // change range 
                try {
                    double a = Double.parseDouble(FromTextField.getText());
                    double b = Double.parseDouble(ToTextField.getText());
                    if (b <= a) {
                        app.showErrorDialog("The specified range is not valid" +
                                "--the upper bound must be greater than the " +
                                "lower bound.");
                        return;
                    }
                    ResultVector = BasicStatistics.changeRange(ColumnVector, a, b);
                    if (ResultVector == null) {
                        app.showErrorDialog("Cannot standardize column " + columnLabel);
                        return;
                    }
                    ParentSpreadsheet.setColumn(storeColumnNumbers[i], 
                            HelperFunctions.ConvertDoubleVectorToString(ResultVector));
                    text += "set range from " + a + " to " + b;
                }
                catch (NumberFormatException e) {
                    app.showErrorDialog("Enter valid bounds for the range.");
                    return;
                }               
            }            
        }
        
        app.addLogParagraph(heading, text);

        app.compoundEdit.end();
        app.addCompoundEdit(app.compoundEdit);
        
        // close dialog
        setVisible(false);
    }//GEN-LAST:event_OKButtonActionPerformed

    private void CancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelButtonActionPerformed
        // close dialog
        setVisible(false);
    }//GEN-LAST:event_CancelButtonActionPerformed

    private void SubtractDivideRadioButtonStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_SubtractDivideRadioButtonStateChanged
        if (SubtractDivideRadioButton.isSelected()) {
            SubtractTextField.setEnabled(true);
            DivideTextField.setEnabled(true);
        }
        else {
            SubtractTextField.setEnabled(false);
            DivideTextField.setEnabled(false);            
        }
    }//GEN-LAST:event_SubtractDivideRadioButtonStateChanged

    private void RangeRadioButtonStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_RangeRadioButtonStateChanged
        if (RangeRadioButton.isSelected()) {
            FromTextField.setEnabled(true);
            ToTextField.setEnabled(true);
        }
        else {
            FromTextField.setEnabled(false);
            ToTextField.setEnabled(false);            
        } 
    }//GEN-LAST:event_RangeRadioButtonStateChanged
    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton CancelButton;
    private javax.swing.JRadioButton DefaultRadioButton;
    private javax.swing.JTextField DivideTextField;
    private javax.swing.JTextField FromTextField;
    private javax.swing.JTextField InputTextField;
    private javax.swing.JButton OKButton;
    private javax.swing.JTextField OutputTextField;
    private javax.swing.JRadioButton RangeRadioButton;
    private javax.swing.JRadioButton SubtractDivideRadioButton;
    private javax.swing.JTextField SubtractTextField;
    private javax.swing.JTextField ToTextField;
    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 jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    // End of variables declaration//GEN-END:variables
    
}
