/*
 * PrintDatasheetDialog.java
 *
 * Created on February 21, 2008, 4:06 PM
 */

package org.statcato.dialogs.file;

import org.statcato.spreadsheet.Spreadsheet;
import org.statcato.statistics.BasicStatistics;
import org.statcato.utils.JFreeReportPrintUtil;
import org.statcato.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
import org.jfree.report.*;
import org.jfree.report.elementfactory.TextFieldElementFactory;
import java.awt.Color;
import java.awt.geom.Rectangle2D;
import java.awt.print.PageFormat;

/**
 * A dialog that provides print options and prints the active Datasheet.
 * Allows the user to specify the print area, header, and footer.
 * 
 * @author  Margaret Yau
 * @version %I%, %G%
 * @see org.jfree.report
 * @since 1.0
 */
public class PrintDatasheetDialog extends StatcatoDialog {
    int [] selectedColumns, selectedRows;
    
    /** Creates new form PrintDatasheetDialog */
    public PrintDatasheetDialog(java.awt.Frame parent, boolean modal, Statcato app) {
        super(parent, modal);
        this.app = app;
        ParentSpreadsheet = app.getSpreadsheet();
        initComponents();
        
        ButtonGroup group = new ButtonGroup();
        group.add(AllRadioButton);
        group.add(SelectionRadioButton);
        group.add(RowColRadioButton);
        RowStartTextField.setEnabled(false);
        RowEndTextField.setEnabled(false);
        ColStartTextField.setEnabled(false);
        ColEndTextField.setEnabled(false);
        
        ItemListener listener = new RadioAction();
        RowColRadioButton.addItemListener(listener);
        SelectionRadioButton.addItemListener(listener);
        AllRadioButton.addItemListener(listener);
        
        // get selected rows and columns indices
        selectedColumns = ParentSpreadsheet.getSelectedColumns();
        selectedRows = ParentSpreadsheet.getSelectedRows();
        
        if (selectedColumns.length != 0 && selectedRows.length != 0)
            SelectionRadioButton.setEnabled(true);
        else
            SelectionRadioButton.setEnabled(false);
        
        getRootPane().setDefaultButton(PrintButton);
        setHelpFile("file-menu");
        name = "Print Datasheet";
        description = "For printing the current datasheet.";
        helpStrings.add("Specify the print area, header, and footer.");
    }
    
    /** 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() {

        jPanel1 = new javax.swing.JPanel();
        HeaderTextField = new javax.swing.JTextField();
        FooterTextField = new javax.swing.JTextField();
        AllRadioButton = new javax.swing.JRadioButton();
        jLabel1 = new javax.swing.JLabel();
        SelectionRadioButton = new javax.swing.JRadioButton();
        RowColRadioButton = new javax.swing.JRadioButton();
        RowStartTextField = new javax.swing.JTextField();
        RowEndLabel = new javax.swing.JLabel();
        RowEndTextField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        ColStartTextField = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        ColEndTextField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        CancelButton = new javax.swing.JButton();
        PrintButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Print Worksheet");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Print Options"));

        HeaderTextField.setText("Worksheet");

        AllRadioButton.setSelected(true);
        AllRadioButton.setText("All");

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel1.setText("Print Area");

        SelectionRadioButton.setText("Selection");

        RowColRadioButton.setText("The following rows and columns:");

        RowEndLabel.setText("to");

        jLabel3.setText("Row");

        jLabel4.setText("Column");

        jLabel5.setText("to");

        jLabel2.setText("Header:");

        jLabel6.setText("Footer:");

        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()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(30, 30, 30)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel3))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(ColStartTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(RowStartTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(RowEndLabel)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(RowEndTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 47, Short.MAX_VALUE))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(jLabel5)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(ColEndTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                            .addComponent(RowColRadioButton, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(AllRadioButton, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(SelectionRadioButton, javax.swing.GroupLayout.Alignment.LEADING))
                        .addGap(216, 216, 216))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel6)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(HeaderTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 233, Short.MAX_VALUE)
                            .addComponent(FooterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap())))
        );

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

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {ColEndTextField, ColStartTextField, RowEndTextField, RowStartTextField});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(AllRadioButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(SelectionRadioButton)
                .addGap(3, 3, 3)
                .addComponent(RowColRadioButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(RowStartTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(RowEndLabel)
                    .addComponent(RowEndTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(ColStartTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(ColEndTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(HeaderTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(10, 10, 10)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(FooterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        CancelButton.setText("Cancel");
        CancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelButtonActionPerformed(evt);
            }
        });

        PrintButton.setText("Print");
        PrintButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                PrintButtonActionPerformed(evt);
            }
        });

        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.PREFERRED_SIZE, 319, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(82, 82, 82)
                        .addComponent(PrintButton)
                        .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, PrintButton});

        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)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(PrintButton)
                    .addComponent(CancelButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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

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

    private void PrintButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PrintButtonActionPerformed
      String header = HeaderTextField.getText();
      String footer = FooterTextField.getText();
      
        Spreadsheet PrintArea = null;
        int minRow = -1, minCol = -1, maxRow = -1, maxCol = -1;
        
        // determine print area
        if (AllRadioButton.isSelected()) {
            // get active area
            int lastrow = ParentSpreadsheet.getLastNonEmptyRow();
            int lastcol = ParentSpreadsheet.getLastNonEmptyColumn();
            PrintArea = ParentSpreadsheet.getSubTable(0, 0, lastrow, lastcol);
        }
        else if (SelectionRadioButton.isSelected()) {
            minRow = BasicStatistics.min(selectedRows);
            minCol = BasicStatistics.min(selectedColumns);
            maxRow = BasicStatistics.max(selectedRows);
            maxCol = BasicStatistics.max(selectedColumns);
            PrintArea = ParentSpreadsheet.getSubTable(minRow, minCol, maxRow, maxCol);
        }
        else if (RowColRadioButton.isSelected()) {
            try {
                minRow = Integer.parseInt(RowStartTextField.getText());
            }
            catch (NumberFormatException e) {
                app.showErrorDialog("Enter a valid starting row number.");
                return;
            }
            try {
                maxRow = Integer.parseInt(RowEndTextField.getText());
            }
            catch (NumberFormatException e) {
                app.showErrorDialog("Enter a valid ending row number.");
                return;
            }     
            try {
                minCol = Integer.parseInt(ColStartTextField.getText());
            }
            catch (NumberFormatException e) {
                app.showErrorDialog("Enter a valid starting column number.");
                return;
            }   
            try {
                maxCol = Integer.parseInt(ColEndTextField.getText());
            }
            catch (NumberFormatException e) {
                app.showErrorDialog("Enter a valid ending column number.");
                return;
            }            
            if (minRow > maxRow) {
                app.showErrorDialog("Starting row number must not be greater than the ending row numbers.");
                return;
            }
            if (minCol > maxCol) {
                app.showErrorDialog("Starting column number must not be greater than the ending column numbers");
                return;
            }
            if (minRow > ParentSpreadsheet.getRowCount() || maxRow > ParentSpreadsheet.getRowCount()) {
                app.showErrorDialog("Enter valid row numbers");
                return;
            }
            if (minCol > ParentSpreadsheet.getColumnCount() || maxCol > ParentSpreadsheet.getColumnCount()) {
                app.showErrorDialog("Enter valid column numbers");
            }
            PrintArea = ParentSpreadsheet.getSubTable(minRow, minCol - 1, maxRow, maxCol - 1);
        }
        
        // use JFreeReport to preview and print spreadsheet
        JFreeReportPrintUtil.PrintControlTable(PrintArea, "", "", header, footer);
        
        /*
        JFreeReportBoot.getInstance().start();
        TableModel model = (TableModel)PrintArea.getModel();        
        
        JFreeReport report = createReportDefinition(model);
        report.setData(model);
        try {
            PreviewDialog preview = new PreviewDialog(report);
            //preview.addWindowListener(new DefaultCloseHandler());
            preview.pack();
            preview.setVisible(true);
        }
        catch (ReportProcessingException e) {
            Log.error("Failed to generate spreadsheet preview", e);
        }
        */
        /*
        try {                       
            PrintArea.display();
            boolean complete = PrintArea.print(mode, header, footer,
                                    true, null, true, null);
            
            if (complete) {
                // show a success message  
                JOptionPane.showMessageDialog(this, "Printing Complete", 
                        "Printing Result", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "Printing Cancelled",
                        "Printing Result", JOptionPane.INFORMATION_MESSAGE);
            }        
        } catch (PrinterException pe) {
            // Printing failed, report to the user 
            JOptionPane.showMessageDialog(this, "Printing Failed: " + pe.getMessage(),
                    "Printing Result", JOptionPane.ERROR_MESSAGE);
        }        
        */
        dispose();
    }//GEN-LAST:event_PrintButtonActionPerformed


    private JFreeReport createReportDefinition(TableModel model)
    {
        JFreeReport report = new JFreeReport();
        report.setName("Datasheet");
        TextFieldElementFactory factory = new TextFieldElementFactory();
        
        
        int numRows = model.getRowCount();
        int numCols = model.getColumnCount();
        TextElement t;
        
        PageFormat ThisPageformat = new PageFormat();
        // have at most 10 columns on one page
        report.setPageDefinition(new SimplePageDefinition(ThisPageformat, 
                (int)Math.ceil(numCols / 10), 1));
        
        for (int i = 0; i < numCols; ++i) {
            t = TextFieldElementFactory.createStringElement(
                "T" + i,
                new Rectangle2D.Double(50*i, 0.0, 50.0, 20.0),
                Color.black,
                ElementAlignment.LEFT,
                ElementAlignment.MIDDLE,
                null, // font
                "-", // null string
                model.getColumnName(i)
                );            
            report.getItemBand().addElement(t);
        }
        
        /*
        TextElement t1 = TextFieldElementFactory.createStringElement(
                "T1",
                new Rectangle2D.Double(0.0, 0.0, 200.0, 50.0),
                Color.black,
                ElementAlignment.LEFT,
                ElementAlignment.MIDDLE,
                null, // font
                "-", // null string
                "Column1"
                );
        report.getItemBand().addElement(t1);
        TextElement t2 = TextFieldElementFactory.createStringElement(
                "T2",
                new Rectangle2D.Double(0.0, 200.0, 200.0, 50.0),
                Color.black,
                ElementAlignment.LEFT,
                ElementAlignment.MIDDLE,
                null, // font
                "-", // null string
                "Column2"
                );
        report.getItemBand().addElement(t2);
         * */
        return report;
    }    
        
    class RadioAction implements ItemListener
    {
        public void itemStateChanged(ItemEvent ie)
        {
            if (RowColRadioButton.isSelected())
            {
                RowStartTextField.setEnabled(true);
                RowEndTextField.setEnabled(true);
                ColStartTextField.setEnabled(true);
                ColEndTextField.setEnabled(true); 
            }
            else {
                RowStartTextField.setEnabled(false);
                RowEndTextField.setEnabled(false);
                ColStartTextField.setEnabled(false);
                ColEndTextField.setEnabled(false);            
            }            
	}
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JRadioButton AllRadioButton;
    private javax.swing.JButton CancelButton;
    private javax.swing.JTextField ColEndTextField;
    private javax.swing.JTextField ColStartTextField;
    private javax.swing.JTextField FooterTextField;
    private javax.swing.JTextField HeaderTextField;
    private javax.swing.JButton PrintButton;
    private javax.swing.JRadioButton RowColRadioButton;
    private javax.swing.JLabel RowEndLabel;
    private javax.swing.JTextField RowEndTextField;
    private javax.swing.JTextField RowStartTextField;
    private javax.swing.JRadioButton SelectionRadioButton;
    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.JPanel jPanel1;
    // End of variables declaration//GEN-END:variables
    
}
