/*
 * DotPlotDialog.java
 *
 * Created on November 19, 2008, 11:27 AM
 */

package org.statcato.dialogs.graph;

import org.statcato.*;
import org.statcato.spreadsheet.*;
import org.statcato.utils.HelperFunctions;

import java.util.*;
import org.jfree.chart.*;
import org.jfree.chart.plot.*;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.chart.renderer.xy.XYDotRenderer;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;

/**
 * A dialog for creating dot plots.
 * 
 * @author  Margaret Yau
 * @version %I%, %G%
 * @see org.jfree.chart
 * @since 1.0
 */
public class DotPlotDialog extends StatcatoDialog {
    
    /** Creates new form DotPlotDialog */
    public DotPlotDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        this.app = (Statcato)parent;
        ParentSpreadsheet = app.getSpreadsheet();
        initComponents();
        customInitComponents();
        setHelpFile("graph-dotplot");
        name = "Dot Plot";
        description = "For creating dot plots showing the occurrences of " +
                "each distinct data value as a stack of dots.";
        helpStrings.add("Select the column variable(s) containing data " +
                "values for which the plot will be created. " +
                "A distinct marker is used with each column variable.");
        helpStrings.add("Enter the plot title, the x-axis label," +
                " and the y-axis label in the corresponding text fields.");
        helpStrings.add("Select the Show Legend check box to show a legend " +
                "indicating the graph variables.");
        pack();
    }
    
    /**
     * 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() {
        updateColumnsList(InputVarList);       
    }
    
    private void customInitComponents() {
        ParentSpreadsheet.populateColumnsList(InputVarList);
        
        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();
        jLabel2 = new javax.swing.JLabel();
        yTextField = new javax.swing.JTextField();
        TitleTextField = new javax.swing.JTextField();
        xTextField = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        LegendCheckBox = new javax.swing.JCheckBox();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        InputVarList = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Dot Plot");

        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("Graph Options"));

        jLabel2.setText("Plot Title:");

        TitleTextField.setText("Dot Plot");

        jLabel4.setText("Y-axis Label:");

        jLabel3.setText("X-axis Label:");

        LegendCheckBox.setSelected(true);
        LegendCheckBox.setText("Show legend");

        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)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(TitleTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(2, 2, 2))
                            .addComponent(xTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE)
                            .addComponent(yTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE))
                        .addContainerGap(70, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(LegendCheckBox)
                        .addContainerGap(267, Short.MAX_VALUE))))
        );

        jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {TitleTextField, xTextField, yTextField});

        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(TitleTextField, 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(jLabel3)
                    .addComponent(xTextField, 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(jLabel4)
                    .addComponent(yTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                .addComponent(LegendCheckBox))
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Graph Variable"));

        jLabel1.setText("Select the column for which the plot will be created:");

        jLabel5.setText("Ctrl-click to select multiple variables");

        jScrollPane1.setViewportView(InputVarList);

        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(jLabel1)
                    .addComponent(jLabel5)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(107, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 146, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(128, 128, 128)
                        .addComponent(OKButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(CancelButton))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .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()
                .addGap(32, 32, 32)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(OKButton)
                    .addComponent(CancelButton))
                .addGap(35, 35, 35))
        );

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

    private void OKButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OKButtonActionPerformed
        app.compoundEdit = new DialogEdit("dot plot");
        
        String heading = "Dot Plot";
        String text = "Input variables: ";
        
        // get selected input variables
        Object[] SelectedColumns = InputVarList.getSelectedValues();
        int[] columnNumbers = ParentSpreadsheet.convertColumnLabelsToNumbers(SelectedColumns);
        
        // check that at least one input variable is selected
        if (columnNumbers.length == 0) {
            app.showErrorDialog("Select at least one input variable.");
            return;
        }
        
        XYSeriesCollection seriesCollection = new XYSeriesCollection();
        TreeMap cumHash = new TreeMap(); // contains the total counts for each distinct data value
        
        for (int i = 0; i < columnNumbers.length; ++i) {            
            Vector<Cell> StrColumnVector = ParentSpreadsheet.getColumn(columnNumbers[i]);
            String columnLabel = (String) SelectedColumns[i];
            text += columnLabel + " ";
            // get input column of doubles
            Vector<Double> ColumnVector = 
                    HelperFunctions.ConvertInputVectorToDoubles(StrColumnVector);
            if (ColumnVector == null) {
                app.showErrorDialog("Invalid input column " + columnLabel +
                        ": all data must be numbers.");
                return;
            }
            seriesCollection.addSeries(makeSeries(columnLabel, ColumnVector, 
                    cumHash));
        }

        app.addLogParagraph(heading, text);        
        app.compoundEdit.end();
        app.addCompoundEdit(app.compoundEdit);

        createPlot(seriesCollection);
        
        setVisible(false);
    }//GEN-LAST:event_OKButtonActionPerformed

    /**
     * Computes the frequency of each distinct data value in the given 
     * vector of data values and creates a XYSeries object containing points 
     * in the dot plot for the frequencies of the data values.  
     * 
     * @param name  String name of the series
     * @param YColumnVector  vector of double values 
     * @param cumHash TreeMap containing the cumulative frequencies of 
     * distinct data values
     * @return XYSeries object
     */
    private XYSeries makeSeries(String name, Vector<Double> YColumnVector,
            TreeMap cumHash) {
        XYSeries series = new XYSeries(name);
        TreeMap hash = HelperFunctions.ComputeFrequency(YColumnVector);
        Set set = hash.keySet();
        Iterator iterator = set.iterator () ; 

        while (iterator.hasNext ())   { 
            Double cat = (Double)iterator.next();
            int count = ((Integer)hash.get(cat)).intValue();
            int offset = 0;
            if (cumHash.containsKey(cat)) {
                offset = ((Integer)cumHash.get(cat)).intValue();
                cumHash.put(cat, new Integer(count + offset));
            }
            else
                cumHash.put(cat, new Integer(count));
            
            for (int i = 1; i <= count; ++i) {
                series.add(cat.doubleValue(), i + offset);
            }
        }          
        return series;
    }
    
    /**
     * Creates a scatterplot given the collection of series objects.
     * 
     * @param data XYSeriesCollection object
     */
    private void createPlot(XYSeriesCollection data) {
        XYDataset data1 = data;
        XYDotRenderer renderer1 = new XYDotRenderer();
        JFreeChart plot = ChartFactory.createScatterPlot(
                TitleTextField.getText(),
                xTextField.getText(),
                yTextField.getText(),
                data1,
                PlotOrientation.VERTICAL,
                LegendCheckBox.isSelected(),
                true,
                false); 
        
        XYPlot xyplot = plot.getXYPlot();
        NumberAxis yaxis = (NumberAxis)xyplot.getRangeAxis();
        yaxis.setTickUnit(new NumberTickUnit(5));        
        StatcatoChartFrame frame =
                new StatcatoChartFrame(TitleTextField.getText(),
                plot, app);
        //frame.setPreferredSize(new java.awt.Dimension(500, maxFreq * 10 + 150));
        frame.pack();
        frame.setVisible(true);          
    }
    
    private void CancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelButtonActionPerformed
        setVisible(false);
    }//GEN-LAST:event_CancelButtonActionPerformed
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton CancelButton;
    private javax.swing.JList InputVarList;
    private javax.swing.JCheckBox LegendCheckBox;
    private javax.swing.JButton OKButton;
    private javax.swing.JTextField TitleTextField;
    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.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField xTextField;
    private javax.swing.JTextField yTextField;
    // End of variables declaration//GEN-END:variables
    
}
