/*
 * GroupsDialog.java
 *
 *  iReport  --  Visual designer for generating JasperReports Documents
 *  Copyright (C) 2002-2003  Giulio Toffoli gt@businesslogic.it
 *
 *  This program is free software; you can redistribute  and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *  Giulio Toffoli
 *  Via T.Aspetti, 233
 *  35100 Padova ITALY
 *  gt@businesslogic.it
 *
 *
 * Created on 10 maggio 2003, 9.51
 */

package it.businesslogic.ireport.gui;

import javax.swing.event.ListSelectionEvent;
import javax.swing.table.*;
import javax.swing.*;
import it.businesslogic.ireport.*;
import it.businesslogic.ireport.util.*;
import it.businesslogic.ireport.gui.event.*;
import java.awt.Point;

import java.util.*;
/**
 *
 * @author  Administrator
 */
public class GroupsDialog extends javax.swing.JDialog {
    
    
    private JReportFrame jReportFrame=null;
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonDeleteGroup;
    private javax.swing.JButton jButtonModifyGroup;
    private javax.swing.JButton jButtonMoveDownGroup;
    private javax.swing.JButton jButtonMoveUpGroup;
    private javax.swing.JButton jButtonNewGroup;
    private javax.swing.JPanel jPanelButtons;
    private javax.swing.JPanel jPanelFields;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTableGroups;
    // End of variables declaration//GEN-END:variables
    
    /**
     * Creates new form GroupsDialog
     */
    public GroupsDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setSize(420, 250);
        Misc.centerFrame(this);
        
        DefaultListSelectionModel dlsm =  (DefaultListSelectionModel)this.jTableGroups.getSelectionModel();
        dlsm.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e)  {
                jTableGroupsListSelectionValueChanged(e);
            }
        });
    }
    
    public void jTableGroupsListSelectionValueChanged(javax.swing.event.ListSelectionEvent e) {
        
        /* Buttons Move Up and Move Down */
        if (this.jTableGroups.getSelectedRowCount() == 1 && this.jTableGroups.getRowCount() > 1) {
            int row= jTableGroups.getSelectedRows()[0];
            this.jButtonMoveDownGroup.setEnabled( row != this.jTableGroups.getRowCount()-1);
            this.jButtonMoveUpGroup.setEnabled( row != 0);
        } else {
            // Moving of multiple groups not allowed
            this.jButtonMoveDownGroup.setEnabled(false);
            this.jButtonMoveUpGroup.setEnabled(false);
        }
        
        /* Other buttons*/
        if (this.jTableGroups.getSelectedRowCount() > 0) {
            this.jButtonModifyGroup.setEnabled(true);
            this.jButtonDeleteGroup.setEnabled(true);
        }
        else {
            this.jButtonModifyGroup.setEnabled(false);
            this.jButtonDeleteGroup.setEnabled(false);
        }
    }
    
    public void updateGroups() {
        
        if (jReportFrame == null) {
            return;
        }
        
        DefaultTableModel dtm = (DefaultTableModel)jTableGroups.getModel();
        dtm.setRowCount(0);
        
        for (Iterator i = jReportFrame.getReport().getGroups().iterator(); i.hasNext(); ) {
            it.businesslogic.ireport.Group group = (it.businesslogic.ireport.Group) i.next();
            Vector row = new Vector();
            row.addElement( group );
            
            dtm.addRow(row);
        }
    }
    
    /** 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() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanelFields = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTableGroups = new javax.swing.JTable();
        jPanelButtons = new javax.swing.JPanel();
        jButtonNewGroup = new javax.swing.JButton();
        jButtonModifyGroup = new javax.swing.JButton();
        jButtonMoveUpGroup = new javax.swing.JButton();
        jButtonMoveDownGroup = new javax.swing.JButton();
        jButtonDeleteGroup = new javax.swing.JButton();

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                closeDialog(evt);
            }
        });

        jPanelFields.setLayout(new java.awt.BorderLayout());

        jScrollPane3.setBackground(new java.awt.Color(255, 255, 255));
        jTableGroups.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Group name"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane3.setViewportView(jTableGroups);

        jPanelFields.add(jScrollPane3, java.awt.BorderLayout.CENTER);

        jPanelButtons.setLayout(new java.awt.GridBagLayout());

        jPanelButtons.setPreferredSize(new java.awt.Dimension(100, 10));
        jPanelButtons.setMinimumSize(new java.awt.Dimension(100, 10));
        jButtonNewGroup.setText("New");
        jButtonNewGroup.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNewGroupActionPerformed(evt);
            }
        });

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(3, 3, 5, 3);
        jPanelButtons.add(jButtonNewGroup, gridBagConstraints);

        jButtonModifyGroup.setText("Modify");
        jButtonModifyGroup.setEnabled(false);
        jButtonModifyGroup.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonModifyGroupActionPerformed(evt);
            }
        });

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 3, 5, 3);
        jPanelButtons.add(jButtonModifyGroup, gridBagConstraints);

        jButtonMoveUpGroup.setText("Move Up");
        jButtonMoveUpGroup.setEnabled(false);
        jButtonMoveUpGroup.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonMoveUpGroupActionPerformed(evt);
            }
        });

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 3, 5, 3);
        jPanelButtons.add(jButtonMoveUpGroup, gridBagConstraints);

        jButtonMoveDownGroup.setText("Move Down");
        jButtonMoveDownGroup.setEnabled(false);
        jButtonMoveDownGroup.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonMoveDownGroupActionPerformed(evt);
            }
        });

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 3, 5, 3);
        jPanelButtons.add(jButtonMoveDownGroup, gridBagConstraints);

        jButtonDeleteGroup.setText("Delete");
        jButtonDeleteGroup.setEnabled(false);
        jButtonDeleteGroup.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDeleteGroupActionPerformed(evt);
            }
        });

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 3, 5, 3);
        jPanelButtons.add(jButtonDeleteGroup, gridBagConstraints);

        jPanelFields.add(jPanelButtons, java.awt.BorderLayout.EAST);

        getContentPane().add(jPanelFields, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    private void jButtonMoveDownGroupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonMoveDownGroupActionPerformed
        if ( jTableGroups.getSelectedRows().length == 1 ) {
            int[] rows= jTableGroups.getSelectedRows();
            Group grp = (Group) jTableGroups.getValueAt( rows[0], 0) ;
            this.getJReportFrame().getReport().moveGroup( grp , 1);  // 1: Forward
            
            // do some administration
            ((MainFrame)this.getParent()).getBandsDialog().updateBands();
            ((MainFrame)this.getParent()).getElementPropertiesDialog().updateSelection();
            this.getJReportFrame().setIsDocDirty(true);
            this.getJReportFrame().repaint();
            updateGroups();
            
            // find position of moved group in the updated list and set focus
            for (int i=0; i <= jTableGroups.getRowCount()-1; i++ ) {
                if ( grp == (Group) jTableGroups.getValueAt(i , 0) ) {
                    jTableGroups.changeSelection( i, 0, true, false );
                    break;
                }
            }
            
            ((MainFrame)this.getParent()).reportBandChanged( new ReportBandChangedEvent(this.getJReportFrame(), null, ReportBandChangedEvent.CHANGED ));
        }
    }//GEN-LAST:event_jButtonMoveDownGroupActionPerformed
    
    private void jButtonMoveUpGroupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonMoveUpGroupActionPerformed
        
        if ( jTableGroups.getSelectedRows().length == 1 ) {
            int[] rows= jTableGroups.getSelectedRows();
            Group grp = (Group) jTableGroups.getValueAt( rows[0], 0) ;
            this.getJReportFrame().getReport().moveGroup( grp , -1); // -1: Backward
            
            // do some administration
            ((MainFrame)this.getParent()).getBandsDialog().updateBands();
            ((MainFrame)this.getParent()).getElementPropertiesDialog().updateSelection();
            this.getJReportFrame().setIsDocDirty(true);
            this.getJReportFrame().repaint();
            updateGroups();
            
            // find position of moved group in the updated list and set focus
            for (int i=0; i <= jTableGroups.getRowCount()-1; i++) {
                if ( grp == (Group) jTableGroups.getValueAt(i , 0) ) {
                    jTableGroups.changeSelection( i, 0, true, false );
                    break;
                }
            }
            
            ((MainFrame)this.getParent()).reportBandChanged( new ReportBandChangedEvent(this.getJReportFrame(), null, ReportBandChangedEvent.CHANGED ));
        }
        
    }//GEN-LAST:event_jButtonMoveUpGroupActionPerformed
    
    private void jButtonDeleteGroupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDeleteGroupActionPerformed
        // jTableGroups.getSelectedRows();  disabled by Robert, July 31, 2004
        
        int[]  rows= jTableGroups.getSelectedRows();
        for (int i=rows.length-1; i>=0; --i) {
            
            // Adjust elements
            Enumeration e = this.getJReportFrame().getReport().getElements().elements();
            while (e.hasMoreElements()) {
                ReportElement re = (ReportElement)e.nextElement();
                if (re.printWhenGroupChanges.equals(""+(it.businesslogic.ireport.Group)jTableGroups.getValueAt( rows[i], 0)) ){
                    re.printWhenGroupChanges = "";
                }
            }
            
            // Adjust variables...
            e = this.getJReportFrame().getReport().getVariables().elements();
            while (e.hasMoreElements()) {
                JRVariable var = (JRVariable)e.nextElement();
                if (var.getResetType().equals("Group") && var.getResetGroup().equals(""+(it.businesslogic.ireport.Group)jTableGroups.getValueAt( rows[i], 0)) ) {
                    var.setResetType("Report");
                    var.setResetGroup("");
                }
            }
            
            this.getJReportFrame().getReport().delGroup((it.businesslogic.ireport.Group)jTableGroups.getValueAt( rows[i], 0));
        }
        updateGroups();
        
        this.getJReportFrame().checkSelection(false);
        ((MainFrame)this.getParent()).getBandsDialog().updateBands();
        ((MainFrame)this.getParent()).getElementPropertiesDialog().updateSelection();
        this.getJReportFrame().setIsDocDirty(true);
        this.getJReportFrame().repaint();
        ((MainFrame)this.getParent()).reportBandChanged( new ReportBandChangedEvent(this.getJReportFrame(), null, ReportBandChangedEvent.REMOVED ));
    }//GEN-LAST:event_jButtonDeleteGroupActionPerformed
    
    private void jButtonModifyGroupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonModifyGroupActionPerformed
        it.businesslogic.ireport.Group group = (it.businesslogic.ireport.Group)jTableGroups.getValueAt( jTableGroups.getSelectedRow(), 0);
        
        JRGroupDialog jrpd = new JRGroupDialog(getJReportFrame(), true);
        jrpd.setGroup( group );
        jrpd.setVisible(true);
        
        if (jrpd.getDialogResult() == javax.swing.JOptionPane.OK_OPTION) {
            
            String oldName = group.getName();
            
            group.setName( jrpd.getGroupName() );
            group.setGroupExpression( jrpd.getExpression());
            group.setIsReprintHeaderOnEachPage(jrpd.isPrintHeaderEachPage() );
            group.setIsResetPageNumber( jrpd.isResetPageNumber()  );
            group.setIsStartNewColumn( jrpd.isStartNewColumn());
            group.setIsStartNewPage( jrpd.isStartNewPage());
            group.setMinHeightToStartNewPage( jrpd.getMinHeightStartNewPage() );
            
            group.getGroupHeader().setName( group.getName()+"Header");
            group.getGroupFooter().setName( group.getName()+"Footer");
            
            int deltaHeader = jrpd.getHeaderBandHeight() - group.getGroupHeader().getHeight();
            int deltaFooter = jrpd.getFooterBandHeight() - group.getGroupFooter().getHeight();
            
            int positionFooterBottom = getJReportFrame().getReport().getBandYLocation( group.getGroupFooter() ) + group.getGroupFooter().getHeight();
            int positionHeaderBottom = getJReportFrame().getReport().getBandYLocation( group.getGroupHeader() ) + group.getGroupHeader().getHeight();
            
            // move down / up all modified bands...
            Enumeration enumElements = getJReportFrame().getReport().getElements().elements();
            while (enumElements.hasMoreElements())
            {
                ReportElement re = (ReportElement)enumElements.nextElement();
                
                if (re.getPosition().getY() >= positionFooterBottom)
                {
                    re.trasform( new Point(0,deltaHeader+deltaFooter), TransformationType.TRANSFORMATION_MOVE);
                }
                else if (re.getPosition().getY() >= positionHeaderBottom)
                {
                    re.trasform( new Point(0,deltaHeader), TransformationType.TRANSFORMATION_MOVE);
                }
            }

            group.getGroupHeader().setHeight(  jrpd.getHeaderBandHeight());
            group.getGroupFooter().setHeight(  jrpd.getFooterBandHeight());
            
            for (int k=getJReportFrame().getReport().getVariables().size()-1; k>=0; --k)
            {
                JRVariable var = (JRVariable)getJReportFrame().getReport().getVariables().elementAt(k);
                if (var.isBuiltin() && var.getName().equalsIgnoreCase(oldName+"_COUNT"))
                {
                    getJReportFrame().getReport().removeVariable(var);
                    break;
                }
            }
            getJReportFrame().getReport().addVariable(new it.businesslogic.ireport.JRVariable(group.getName()+"_COUNT","java.lang.Integer", true));
            
            
            // Update All variables...
            Enumeration e = getJReportFrame().getReport().getVariables().elements();
            while (e.hasMoreElements()) {
                JRVariable var = (JRVariable)e.nextElement();
                if (var.getResetGroup() != null &&
                var.getResetGroup().equals(oldName)) {
                    var.setResetGroup( group.getName() );
                }
            }
            
            // Adjust elements
            e = this.getJReportFrame().getReport().getElements().elements();
            while (e.hasMoreElements()) {
                ReportElement re = (ReportElement)e.nextElement();
                if (re.printWhenGroupChanges.equals(oldName) )
                    re.printWhenGroupChanges = group.getName();
                
                if (re instanceof TextFieldReportElement &&
                ((TextFieldReportElement)re).getGroup().equals(oldName))
                    ((TextFieldReportElement)re).setGroup(group.getName());
            }
            
            
            
            // refersh bands frame....
            ((MainFrame)this.getParent()).getBandsDialog().updateBands();
            ((MainFrame)this.getParent()).getElementPropertiesDialog().updateSelection();
            this.getJReportFrame().setIsDocDirty(true);
            this.getJReportFrame().repaint();
            this.updateGroups();
            ((MainFrame)this.getParent()).reportBandChanged( new ReportBandChangedEvent(this.getJReportFrame(), null, ReportBandChangedEvent.CHANGED ));
        }
        
    }//GEN-LAST:event_jButtonModifyGroupActionPerformed
    
    private void jButtonNewGroupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNewGroupActionPerformed
        JRGroupDialog jrpd = new JRGroupDialog(this.getJReportFrame(), true);
        jrpd.setVisible(true);
        
        if (jrpd.getDialogResult() == javax.swing.JOptionPane.OK_OPTION) {
            Group g = new it.businesslogic.ireport.Group(this.getJReportFrame().getReport(), jrpd.getGroupName());
            g.setGroupExpression( jrpd.getExpression());
            g.setIsReprintHeaderOnEachPage(jrpd.isPrintHeaderEachPage() );
            g.setIsResetPageNumber( jrpd.isResetPageNumber()  );
            g.setIsStartNewColumn( jrpd.isStartNewColumn());
            g.setIsStartNewPage( jrpd.isStartNewPage());
            g.setMinHeightToStartNewPage( jrpd.getMinHeightStartNewPage() );
            
            g.getGroupHeader().setHeight(  jrpd.getHeaderBandHeight());
            g.getGroupFooter().setHeight(  jrpd.getFooterBandHeight());
            
            this.getJReportFrame().getReport().addGroup(g);
            this.getJReportFrame().setIsDocDirty(true);
            this.getJReportFrame().repaint();
            this.updateGroups();
            
            // refersh bands frame....
            ((MainFrame)this.getParent()).getBandsDialog().updateBands();
            ((MainFrame)this.getParent()).getElementPropertiesDialog().updateBands();
            ((MainFrame)this.getParent()).getElementPropertiesDialog().updateGroups();
            ((MainFrame)this.getParent()).reportBandChanged( new ReportBandChangedEvent(this.getJReportFrame(), null, ReportBandChangedEvent.ADDED ));
        }
    }//GEN-LAST:event_jButtonNewGroupActionPerformed
    
    /** Closes the dialog */
    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
        setVisible(false);
        dispose();
    }//GEN-LAST:event_closeDialog
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        new GroupsDialog(new javax.swing.JFrame(), true).setVisible(true);
    }
    
    /** Getter for property jReportFrame.
     * @return Value of property jReportFrame.
     *
     */
    public it.businesslogic.ireport.gui.JReportFrame getJReportFrame() {
        return jReportFrame;
    }
    
    /** Setter for property jReportFrame.
     * @param jReportFrame New value of property jReportFrame.
     *
     */
    public void setJReportFrame(it.businesslogic.ireport.gui.JReportFrame jReportFrame) {
        this.jReportFrame = jReportFrame;
        
        // Update all...
        if (jReportFrame == null) {
            setVisible(false);
            return;
        }
        this.setTitle(jReportFrame.getReport().getName()+" groups...");
        if (isVisible()) {
            updateGroups();
        }
    }
    
    
    public void setVisible(boolean visible) {
        if (visible == isVisible()) return;
        super.setVisible(visible);
        if (visible == true) {
            this.setJReportFrame(jReportFrame);
        }
    }
}
