/*
 * BandsDialog.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.table.*;
import javax.swing.*;
import javax.swing.event.*;
import it.businesslogic.ireport.*;
import it.businesslogic.ireport.util.*;

import java.util.*;
/**
 *
 * @author  Administrator
 */
public class BandsDialog extends javax.swing.JDialog {
    
    
    private JReportFrame jReportFrame=null;
    
    /** Creates new form BandsDialog */
    public BandsDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
         this.setSize(720, 400);
         Misc.centerFrame(this);
         jListBands.setModel(new DefaultListModel());      
         
         
         this.jRTextExpressionArea.getDocument().addDocumentListener( new javax.swing.event.DocumentListener() {
            public void changedUpdate(javax.swing.event.DocumentEvent evt)
            {
                jRTextExpressionAreaTextChanged();
            }
            public void insertUpdate(javax.swing.event.DocumentEvent evt) {
                jRTextExpressionAreaTextChanged();
            }
            public void removeUpdate(javax.swing.event.DocumentEvent evt) {
                jRTextExpressionAreaTextChanged();
            }
        }); 
         
         
    }
    
    
    private void jRTextExpressionAreaTextChanged()
    {
        if (jListBands.getSelectedValue()!= null &&
            jListBands.getSelectedValue() instanceof Band)
        {
            Band selectedBand = (Band)jListBands.getSelectedValue();
            selectedBand.setPrintWhenExpression( jRTextExpressionArea.getText() );
        }
    }
    
    public void jTableBandsListSelectionValueChanged(javax.swing.event.ListSelectionEvent e)
    {
       
    }
    
     public void updateBands() {
    
         Object selected = jListBands.getSelectedValue();
         boolean isSelected = false;

        ((DefaultListModel)jListBands.getModel()).removeAllElements();
    
        if (jReportFrame == null) return;
        Enumeration e = jReportFrame.getReport().getBands().elements();
        while (e.hasMoreElements())
        {
            it.businesslogic.ireport.Band band = (it.businesslogic.ireport.Band)e.nextElement();
            ((DefaultListModel)jListBands.getModel()).addElement(band);    
            if (selected == band)
            {
                jListBands.setSelectedValue(selected, true);
                isSelected = true;
            }
        }    
        
        if (!isSelected && jReportFrame.getReport().getBands().size() > 0)
        {
            jListBands.setSelectedIndex(0);
        }
    }
    /** 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.
     */
        private void initComponents() {//GEN-BEGIN:initComponents
                java.awt.GridBagConstraints gridBagConstraints;

                jPanelFields = new javax.swing.JPanel();
                jPanelButtons = new javax.swing.JPanel();
                jPanel2 = new javax.swing.JPanel();
                jPanel3 = new javax.swing.JPanel();
                jLabel1 = new javax.swing.JLabel();
                jLabel2 = new javax.swing.JLabel();
                jNumberFieldHeight = new it.businesslogic.ireport.gui.JNumberField();
                jCheckBoxSplitAllowed = new javax.swing.JCheckBox();
                jRTextExpressionArea = new it.businesslogic.ireport.gui.JRTextExpressionArea();
                jScrollPane1 = new javax.swing.JScrollPane();
                jListBands = new javax.swing.JList();

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

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

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

                jPanelButtons.setBorder(new javax.swing.border.TitledBorder(new javax.swing.border.EtchedBorder(), "Band properties", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 11)));
                jPanelButtons.setMinimumSize(new java.awt.Dimension(100, 10));
                jPanelButtons.setPreferredSize(new java.awt.Dimension(100, 10));
                jPanel2.setLayout(new java.awt.BorderLayout());

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

                jPanel3.setPreferredSize(new java.awt.Dimension(10, 55));
                jLabel1.setFont(new java.awt.Font("Dialog", 0, 11));
                jLabel1.setText("Print When Expression");
                gridBagConstraints = new java.awt.GridBagConstraints();
                gridBagConstraints.gridx = 0;
                gridBagConstraints.gridy = 2;
                gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
                gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
                jPanel3.add(jLabel1, gridBagConstraints);

                jLabel2.setFont(new java.awt.Font("Dialog", 0, 11));
                jLabel2.setText("Band height");
                gridBagConstraints = new java.awt.GridBagConstraints();
                gridBagConstraints.gridx = 0;
                gridBagConstraints.gridy = 0;
                gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
                gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
                jPanel3.add(jLabel2, gridBagConstraints);

                jNumberFieldHeight.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
                jNumberFieldHeight.setText("0");
                try {
                        jNumberFieldHeight.setDecimals(0);
                } catch (java.beans.PropertyVetoException e1) {
                        e1.printStackTrace();
                }
                jNumberFieldHeight.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                                jNumberFieldHeightActionPerformed(evt);
                        }
                });

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

                jCheckBoxSplitAllowed.setFont(new java.awt.Font("Dialog", 0, 11));
                jCheckBoxSplitAllowed.setText("Split allowed");
                jCheckBoxSplitAllowed.setSelected(true);
                jCheckBoxSplitAllowed.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                                jCheckBoxSplitAllowedActionPerformed(evt);
                        }
                });

                gridBagConstraints = new java.awt.GridBagConstraints();
                gridBagConstraints.gridx = 1;
                gridBagConstraints.gridy = 0;
                gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
                gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
                jPanel3.add(jCheckBoxSplitAllowed, gridBagConstraints);

                jRTextExpressionArea.setBorder(new javax.swing.border.EtchedBorder());
                jRTextExpressionArea.setMinimumSize(new java.awt.Dimension(0, 0));
                jRTextExpressionArea.setElectricScroll(0);
                gridBagConstraints = new java.awt.GridBagConstraints();
                gridBagConstraints.gridx = 0;
                gridBagConstraints.gridy = 3;
                gridBagConstraints.gridwidth = 2;
                gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
                gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
                gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
                gridBagConstraints.weightx = 1.0;
                gridBagConstraints.weighty = 1.0;
                jPanel3.add(jRTextExpressionArea, gridBagConstraints);

                jPanel2.add(jPanel3, java.awt.BorderLayout.CENTER);

                jPanelButtons.add(jPanel2, java.awt.BorderLayout.CENTER);

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

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

                jScrollPane1.setToolTipText("");
                jScrollPane1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
                jScrollPane1.setPreferredSize(new java.awt.Dimension(150, 131));
                jListBands.setBorder(new javax.swing.border.EtchedBorder());
                jListBands.setFont(new java.awt.Font("Dialog", 0, 11));
                jListBands.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
                jListBands.setToolTipText("List of bands");
                jListBands.setMaximumSize(new java.awt.Dimension(32767, 32767));
                jListBands.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
                        public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                                jListBandsValueChanged(evt);
                        }
                });

                jScrollPane1.setViewportView(jListBands);

                getContentPane().add(jScrollPane1, java.awt.BorderLayout.WEST);

                pack();
        }//GEN-END:initComponents

    private void jCheckBoxSplitAllowedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxSplitAllowedActionPerformed
        
        Band b = (Band)this.jListBands.getSelectedValue();
        if (b != null) b.setSplitAllowed( jCheckBoxSplitAllowed.isSelected());
        
    }//GEN-LAST:event_jCheckBoxSplitAllowedActionPerformed

    private void jNumberFieldHeightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jNumberFieldHeightActionPerformed
        
        
        Band b = (Band)this.jListBands.getSelectedValue();
	// 1. we set band height, but first we adjust elements position
	int delta = (int)jNumberFieldHeight.getValue() - b.getHeight();
	if (delta != 0)
	{
                Report report = getJReportFrame().getReport();
		int min_height = 0;
		int band_h =  getJReportFrame().getReport().getBandYLocation(b) +10;
		if (delta < -(  b.getHeight()-min_height) ) delta= -(b.getHeight()-min_height);
                //if (report.getDesignHeightNoBG()+delta > report.getPagesize().y) delta = report.getPagesize().y- report.getDesignHeightNoBG();
					    
		if (!b.getName().equals("background") &&
                    !( b.getName().equals("title") && getJReportFrame().getReport().isIsTitleNewPage()) &&
                    !( b.getName().equals("summary") && getJReportFrame().getReport().isIsSummaryNewPage()))
                {
                    int designHeight = report.getDesignHeightNoBG();
                    if (report.isIsTitleNewPage())
                    {
                        designHeight -= report.getBandByName("title").getHeight();
                    }

                    if (report.isIsSummaryNewPage())
                    {
                        designHeight -= report.getBandByName("summary").getHeight();
                    }
                    
                    if (designHeight+delta > report.getHeight())
                    {
                        delta = report.getHeight()- designHeight;
                    }
                }
		else
                {
                    if (b.getHeight()+delta > report.getHeight()-report.getTopMargin()- report.getBottomMargin())
                    {
                        delta = report.getHeight()-b.getHeight()-report.getTopMargin()-report.getBottomMargin();
                    }
                }
						
		// Redraw all under the min height...
		b.setHeight( b.getHeight() + delta );
		int edge_y =  Math.min(report.getBandYLocation(b)+b.getHeight(),report.getBandYLocation(b)+b.getHeight()-delta);
		Enumeration e = report.getElements().elements();
		while (e.hasMoreElements())
		{
			ReportElement re = (ReportElement)e.nextElement();
			if (re.position.y >= edge_y+10)	
			{
				// I should add the distance form the base of resized band, and my element... 
                		int space_before_band = band_h - re.position.y - re.height;
				if (band_h <= report.getBandYLocation(re.getBand()) +10)
				space_before_band = 0;
				re.setPosition(new java.awt.Point(re.getPosition().x, re.getPosition().y+delta));	
                        }	
		}	
                
                try {
                    jNumberFieldHeight.setValue(b.getHeight());
                } catch (Exception ex){}
                //System.out.println("Repaint");
                getJReportFrame().setIsDocDirty(true);
                getJReportFrame().updateScrollBars();
                getJReportFrame().getReportPanel().repaint();
	}
                                        
    }//GEN-LAST:event_jNumberFieldHeightActionPerformed

    private void jListBandsValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListBandsValueChanged
        //
        if (jListBands.getModel().getSize() == 0)
        {
             try {
                this.jNumberFieldHeight.setValue( 0 );
            } catch (Exception ex) {}
            this.jRTextExpressionArea.setText("");
             jCheckBoxSplitAllowed.setSelected(false);
            return;
        }
        
        if (jListBands.getSelectedIndex() < 0) 
        {
            jListBands.setSelectedIndex(0);
            return;
        }
        Band selectedBand = (Band)jListBands.getSelectedValue();
        try {
            this.jNumberFieldHeight.setValue( selectedBand.getHeight());
        } catch (Exception ex) {}
        this.jRTextExpressionArea.setText( selectedBand.getPrintWhenExpression());
        this.jCheckBoxSplitAllowed.setSelected(  selectedBand.isSplitAllowed() );
    }//GEN-LAST:event_jListBandsValueChanged
    
    /** 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 BandsDialog(new javax.swing.JFrame(), true).show();
    }
    
    /** 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()+" bands...");
        if (isVisible())
        {
            updateBands();
        }
    }
    
        // Variables declaration - do not modify//GEN-BEGIN:variables
        private javax.swing.JCheckBox jCheckBoxSplitAllowed;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JList jListBands;
        private it.businesslogic.ireport.gui.JNumberField jNumberFieldHeight;
        private javax.swing.JPanel jPanel2;
        private javax.swing.JPanel jPanel3;
        private javax.swing.JPanel jPanelButtons;
        private javax.swing.JPanel jPanelFields;
        private it.businesslogic.ireport.gui.JRTextExpressionArea jRTextExpressionArea;
        private javax.swing.JScrollPane jScrollPane1;
        // End of variables declaration//GEN-END:variables
    
    public void setVisible(boolean visible)
    {
        if (visible == isVisible()) return;
        super.setVisible(visible);
        if (visible == true) 
        {
            this.setJReportFrame(jReportFrame);
        }
    }
    
    public void setSelectedBand(String bandName )
    {
        for (int i=0; i<jListBands.getModel().getSize(); ++i)
        {
            Band b = (Band)jListBands.getModel().getElementAt( i );
            if (b.getName().equals(bandName))
            {
                jListBands.setSelectedIndex( i );
                return;
            }
        }
    }
}
