/*
 * WizardDialog.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 it 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
 *
 *
 * How this window work.
 * This form has an attribute that rappresents the JReportForm active.
 * If the jrf is null, this frame hides.
 * When something changes, the program can call "updateSelection". This
 * class retrive from jrf the selected elements and update all
 * interface.
 *
 * Created on 30 giugno 2003, 18.26
 */

package it.businesslogic.ireport.gui;
import it.businesslogic.ireport.IReportConnection;
import it.businesslogic.ireport.connection.JDBCConnection;
import it.businesslogic.ireport.connection.JRCSVDataSourceConnection;
import it.businesslogic.ireport.connection.JRDataSourceProviderConnection;
import it.businesslogic.ireport.connection.JRHibernateConnection;
import it.businesslogic.ireport.connection.JavaBeanDataSourceConnection;
import it.businesslogic.ireport.util.*;
import it.businesslogic.ireport.*;
import java.sql.*;
import java.util.*;
import java.io.*;
import javax.swing.DefaultListModel;

import org.apache.xerces.parsers.DOMParser;
import org.apache.xpath.XPathAPI;
import org.apache.xpath.objects.XBoolean;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.DOMException;

import org.xml.sax.SAXException;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

/**
 *
 * @author  Administrator
 */
public class WizardDialog extends javax.swing.JDialog implements Runnable, LanguageChangedListener {
//Modified by Felix Firgau on Feb 8th 2006

    Thread t = null;
    Vector templates = null;
    org.syntax.jedit.JEditTextArea jRSQLExpressionArea1 = null;

    /** Creates new form WizardDialog */
    public WizardDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        //Added by Felix Firgau for I18n on Feb 8th 2006
        it.businesslogic.ireport.util.I18n.setCurrentLocale( System.getProperty("Language"), System.getProperty("Country") );

        templates = new Vector();

        jRSQLExpressionArea1 = new org.syntax.jedit.JEditTextArea();
        jRSQLExpressionArea1.getPainter().setLineHighlightColor(java.awt.Color.WHITE);
        jRSQLExpressionArea1.setDocument(new org.syntax.jedit.SyntaxDocument());
        jRSQLExpressionArea1.setTokenMarker(new org.syntax.jedit.tokenmarker.TSQLTokenMarker());
        jRSQLExpressionArea1.setAutoscrolls(true);

        java.awt.GridBagConstraints gridBagConstraints= null;
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        //gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;

        jPanel1.add(jRSQLExpressionArea1, gridBagConstraints);

        wzStep = 1;
        this.setStep(wzStep,wzStep);
        this.setSize(480, 350);
        Misc.centerFrame(this);



        this.jRSQLExpressionArea1.getDocument().addDocumentListener( new javax.swing.event.DocumentListener() {
            public void changedUpdate(javax.swing.event.DocumentEvent evt) {
                jRSQLExpressionArea1TextConnectionExpressionTextChanged();
            }
            public void insertUpdate(javax.swing.event.DocumentEvent evt) {
                jRSQLExpressionArea1TextConnectionExpressionTextChanged();
            }
            public void removeUpdate(javax.swing.event.DocumentEvent evt) {
                jRSQLExpressionArea1TextConnectionExpressionTextChanged();
            }
        });

        this.jTextFieldBean.getDocument().addDocumentListener( new javax.swing.event.DocumentListener() {
            public void changedUpdate(javax.swing.event.DocumentEvent evt) {
                jRSQLExpressionArea1TextConnectionExpressionTextChanged();
            }
            public void insertUpdate(javax.swing.event.DocumentEvent evt) {
                jRSQLExpressionArea1TextConnectionExpressionTextChanged();
            }
            public void removeUpdate(javax.swing.event.DocumentEvent evt) {
                jRSQLExpressionArea1TextConnectionExpressionTextChanged();
            }
        });

        this.jRSQLExpressionArea1.requestFocusInWindow();
        jList1.setModel(new javax.swing.DefaultListModel());
        jList2.setModel(new javax.swing.DefaultListModel());
        jList3.setModel(new javax.swing.DefaultListModel());

        String templates_dir = MainFrame.IREPORT_HOME_DIR;  //System.getProperty("ireport.home",".");
        templates_dir +=  File.separator + "templates";
        //System.out.println("Templates: " + templates_dir);
        //C:\\documenti\\progetti\\ireport\\iReport2\\templates
        try {
            File f = new File(templates_dir);
            File[] templates_files = null;
            if (f.exists() && f.isDirectory()) {
                templates_files  = f.listFiles(new FilenameFilter() {
                    public boolean accept(File dir, String name) {
                        if (name.endsWith("T.xml") || name.endsWith("C.xml")) {
                            return true;
                        }
                        return false;
                    }
                });
            } else {
                templates_dir = MainFrame.IREPORT_HOME_DIR;  //System.getProperty("ireport.home",".");
                templates_dir +=  File.separator + "etc" + File.separator + "templates";
                f = new File(templates_dir);
                if (f.exists() && f.isDirectory()) {
                    templates_files  = f.listFiles(new FilenameFilter() {
                        public boolean accept(File dir, String name) {
                            if (name.endsWith("T.xml") || name.endsWith("C.xml")) {
                                return true;
                            }
                            return false;
                        }
                    });
                }
            }

            for (int i=0;templates_files != null && i<templates_files.length; ++i) {
                IReportTemplate itemplate = new IReportTemplate();
                itemplate.setXmlFile(templates_files[i] +"");
                itemplate.setName(templates_files[i].getName());
                itemplate.setType( templates_files[i].getName().toLowerCase().endsWith("c.xml") ? 0 : 1);
                try {
                    String iconname = templates_files[i]+"";
                    iconname = Misc.changeFileExtension(iconname,".gif");
                    itemplate.setIcon( new javax.swing.ImageIcon( iconname) );
                } catch (Exception ex){}

                templates.add( itemplate );
            }

        } catch (Exception ex) {
        }


        // try to look in the classpath...
        try {
            Vector xml_template_files = new Vector();
            Enumeration enum_pl = this.getClass().getClassLoader().getResources("ireport/template.xml");
            while (enum_pl.hasMoreElements()) {
                Object oobj = enum_pl.nextElement();
                xml_template_files.add(oobj);
            }

            for (int i=0; i<xml_template_files.size(); ++i) {

                Object source = xml_template_files.elementAt(i);
                //  Create a Xerces DOM Parser
                DOMParser parser = new DOMParser();
                //  Parse the Document
                //  and traverse the DOM
                try {

                    parser.setEntityResolver( new org.xml.sax.EntityResolver() {
                        /* Code by Teodor Danciu */
                        public org.xml.sax.InputSource resolveEntity(
                                String publicId,
                                String systemId
                                ) throws SAXException//, java.io.IOException
                        {
                            org.xml.sax.InputSource inputSource = null;

                            if (systemId != null) {
                                String dtd = null;

                                if ( systemId.equals("http://ireport.sourceforge.net/dtds/iReportTemplate.dtd") ) {
                                    dtd = "it/businesslogic/ireport/dtds/iReportTemplate.dtd";
                                } else {
                                    return new org.xml.sax.InputSource(systemId);
                                }


                                ClassLoader classLoader = this.getClass().getClassLoader();

                                java.io.InputStream is = classLoader.getResourceAsStream(dtd);
                                if (is != null) {
                                    inputSource = new org.xml.sax.InputSource(is);
                                }

                            }

                            return inputSource;
                        }
                    });
                    /* End Code by Teodor Danciu */
                    InputStream input_source = null;
                    if ( source instanceof java.io.File ) {
                        input_source = new FileInputStream((java.io.File)source);

                    } else if ( source instanceof java.net.URL){

                        input_source = ((java.net.URL)source).openStream();

                    }

                    parser.parse(new org.xml.sax.InputSource( input_source ));
                    Document document = parser.getDocument();

                    //System.out.println("traverse");
                    Node node = document.getDocumentElement();

                    NodeList list = XPathAPI.selectNodeList(node, "/iReportTemplateSet/iReportTemplate");
                    Node childnode = null;

                    for (int n=0; n < list.getLength(); n++) {
                        IReportTemplate ireportTemplate = new IReportTemplate();
                        childnode = XPathAPI.selectSingleNode(list.item(n), "@name");
                        if (childnode != null) ireportTemplate.setName(childnode.getNodeValue());
                        if (XPathAPI.eval(list.item(n), "@type = 'Tabular'").equals(XBoolean.S_TRUE)) {
                            ireportTemplate.setType(IReportTemplate.TABULAR);
                        } else {
                            ireportTemplate.setType(IReportTemplate.COLUMNAR);
                        }
                        childnode = XPathAPI.selectSingleNode(list.item(n), "XmlFile/text()");
                        if (childnode != null) ireportTemplate.setXmlFile(childnode.getNodeValue());
                        childnode = XPathAPI.selectSingleNode(list.item(n), "IconFile/text()");
                        if (childnode != null) {
                            try {
                                ireportTemplate.setIcon(
                                        new ImageIcon(getClass().getClassLoader().getResource(childnode.getNodeValue())));
                            } catch (DOMException e) {
                                // Don't care
                                e.printStackTrace();
                            }
                        }

                        templates.add(ireportTemplate);
                    }
                } catch (SAXException e) {
                    System.err.println(e);
                } catch (java.io.IOException e) {
                    System.err.println(e);
                }
            } // End cycle on iReport plugin files...

        } catch (Exception ex) {
            MainFrame.getMainInstance().logOnConsole("Error searching ireport/template.xml resources\n");
        }

        updateTemplatesList();
        //jRSQLExpressionArea1.setText("00000000000000000000000000000000000000000000000000000\n\r");

        //this.pack();
        updateConnections();

    }

    public void updateConnections() {
        Object ircDefault =  MainFrame.getMainInstance().getProperties().get("DefaultConnection");
        jComboBoxConnection.removeAllItems();

        Enumeration e = MainFrame.getMainInstance().getConnections().elements();
        while (e.hasMoreElements()) {
            IReportConnection irc = (IReportConnection)e.nextElement();
            jComboBoxConnection.addItem(irc);
        }

        if (ircDefault != null) {
            jComboBoxConnection.setSelectedItem(ircDefault);
        }
    }

    private int wzStep=0;


    public void updateTemplatesList() {
        if (templates == null) return;
        ((javax.swing.DefaultListModel)jList3.getModel()).removeAllElements();

        for (int i=0;  i< templates.size(); ++i) {
            IReportTemplate itemplate = (IReportTemplate)templates.elementAt(i);

            if (jRadioButtonTabularLayout.isSelected() && itemplate.getType() != IReportTemplate.TABULAR) continue;
            if (jRadioButtonColumnarLayout.isSelected() && itemplate.getType() != IReportTemplate.COLUMNAR) continue;
            //if (jComboBoxTemplates.getItemCount()<2 || (jComboBoxTemplates.getSelectedIndex() == 0 && itemplate.getType() != IReportTemplate.COLUMNAR) )  continue;
            //if (jComboBoxTemplates.getSelectedIndex() == 1 && itemplate.getType() != IReportTemplate.TABULAR)  continue;
            /*
            TemplateFile tf = new TemplateFile();
            tf.file = templates[i];

            tf.name = templates[i].getName().substring(0, templates[i].getName().length()-4);
             */
            ((javax.swing.DefaultListModel)jList3.getModel()).addElement(itemplate);
        }
        if ( ((javax.swing.DefaultListModel)jList3.getModel()).getSize()>0)
            jList3.setSelectedIndex(0);
        jList3.updateUI();
    }

    public void jRSQLExpressionArea1TextConnectionExpressionTextChanged() {
        jComboBoxConnectionActionPerformed(null);

    }


    /** 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() {
        buttonGroup1 = new javax.swing.ButtonGroup();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        jLabel1 = new javax.swing.JLabel();
        jLabelStep1 = new javax.swing.JLabel();
        jLabelStep2 = new javax.swing.JLabel();
        jLabelStep3 = new javax.swing.JLabel();
        jLabelStep4 = new javax.swing.JLabel();
        jLabelStep5 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jButtonCancel = new javax.swing.JButton();
        jButtonNext = new javax.swing.JButton();
        jButtonPrev = new javax.swing.JButton();
        jPanelRoot = new javax.swing.JPanel();
        jPanelStep1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jSeparator3 = new javax.swing.JSeparator();
        jPanel1 = new javax.swing.JPanel();
        jComboBoxConnection = new javax.swing.JComboBox();
        jLabel12 = new javax.swing.JLabel();
        jButtonNewConnection = new javax.swing.JButton();
        jTextFieldBean = new javax.swing.JTextField();
        jButtonLoadQuery = new javax.swing.JButton();
        jButtonSaveQuery = new javax.swing.JButton();
        jPanelStep3 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        jSeparator5 = new javax.swing.JSeparator();
        jComboBox1 = new javax.swing.JComboBox();
        jLabelG1 = new javax.swing.JLabel();
        jLabelG2 = new javax.swing.JLabel();
        jComboBox2 = new javax.swing.JComboBox();
        jLabelG3 = new javax.swing.JLabel();
        jComboBox3 = new javax.swing.JComboBox();
        jLabelG4 = new javax.swing.JLabel();
        jComboBox4 = new javax.swing.JComboBox();
        jPanelStep5 = new javax.swing.JPanel();
        jLabel9 = new javax.swing.JLabel();
        jSeparator7 = new javax.swing.JSeparator();
        jLabel4 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jPanelStep2 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jSeparator4 = new javax.swing.JSeparator();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jPanelStep4 = new javax.swing.JPanel();
        jLabel8 = new javax.swing.JLabel();
        jSeparator6 = new javax.swing.JSeparator();
        jScrollPane3 = new javax.swing.JScrollPane();
        jList3 = new javax.swing.JList();
        jLabelImage = new javax.swing.JLabel();
        jRadioButtonColumnarLayout = new javax.swing.JRadioButton();
        jRadioButtonTabularLayout = new javax.swing.JRadioButton();

        getContentPane().setLayout(null);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        //Modified by Felix Firgau for I18n on Feb 8th 2006
        setTitle(it.businesslogic.ireport.util.I18n.getString("reportWizard", "Report wizard")); //Modification end
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                closeDialog(evt);
            }
        });

        getContentPane().add(jSeparator1);
        jSeparator1.setBounds(2, 280, 460, 4);

        jSeparator2.setBackground(new java.awt.Color(204, 204, 255));
        jSeparator2.setForeground(new java.awt.Color(0, 0, 0));
        jSeparator2.setMaximumSize(new java.awt.Dimension(32767, 1));
        jSeparator2.setMinimumSize(new java.awt.Dimension(98, 1));
        jSeparator2.setPreferredSize(new java.awt.Dimension(1, 1));
        getContentPane().add(jSeparator2);
        jSeparator2.setBounds(8, 28, 98, 2);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel1.setText("Steps");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(8, 10, 84, 16);

        jLabelStep1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabelStep1.setText("1. Query");
        getContentPane().add(jLabelStep1);
        jLabelStep1.setBounds(8, 34, 110, 16);

        jLabelStep2.setText("2. Fields selection");
        getContentPane().add(jLabelStep2);
        jLabelStep2.setBounds(8, 52, 110, 16);

        jLabelStep3.setText("3. Group by ...");
        getContentPane().add(jLabelStep3);
        jLabelStep3.setBounds(8, 70, 110, 16);

        jLabelStep4.setText("4. Layout");
        getContentPane().add(jLabelStep4);
        jLabelStep4.setBounds(8, 88, 110, 16);

        jLabelStep5.setText("5. Finish");
        getContentPane().add(jLabelStep5);
        jLabelStep5.setBounds(8, 106, 110, 16);

        jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/it/businesslogic/ireport/icons/wizard.jpg")));
        getContentPane().add(jLabel7);
        jLabel7.setBounds(0, 0, 132, 284);

        jButtonCancel.setMnemonic('f');
        //Modified by Felix Firgau for I18N on Mar 2nd 2006
        jButtonCancel.setText(it.businesslogic.ireport.util.I18n.getString("cancel", "Cancel"));//End
        jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelActionPerformed(evt);
            }
        });

        getContentPane().add(jButtonCancel);
        jButtonCancel.setBounds(384, 286, 76, 24);

        jButtonNext.setMnemonic('n');
        jButtonNext.setText("Next >");
        jButtonNext.setEnabled(false);
        jButtonNext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNextActionPerformed(evt);
            }
        });

        getContentPane().add(jButtonNext);
        jButtonNext.setBounds(302, 286, 76, 24);

        jButtonPrev.setMnemonic('p');
        jButtonPrev.setText("< Prev");
        jButtonPrev.setEnabled(false);
        jButtonPrev.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonPrevActionPerformed(evt);
            }
        });

        getContentPane().add(jButtonPrev);
        jButtonPrev.setBounds(220, 286, 76, 24);

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

        jPanelStep1.setLayout(null);

        jLabel2.setText("Query string");
        jPanelStep1.add(jLabel2);
        jLabel2.setBounds(0, 134, 300, 14);

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel3.setText("Step 1: insert the query to retrive report fields");
        jPanelStep1.add(jLabel3);
        jLabel3.setBounds(0, 10, 298, 16);

        jSeparator3.setBackground(new java.awt.Color(204, 204, 204));
        jSeparator3.setForeground(new java.awt.Color(0, 0, 0));
        jSeparator3.setMaximumSize(new java.awt.Dimension(32767, 1));
        jSeparator3.setMinimumSize(new java.awt.Dimension(98, 1));
        jSeparator3.setPreferredSize(new java.awt.Dimension(10, 1));
        jPanelStep1.add(jSeparator3);
        jSeparator3.setBounds(0, 28, 300, 2);

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

        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        jPanelStep1.add(jPanel1);
        jPanel1.setBounds(0, 150, 300, 100);

        jComboBoxConnection.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jComboBoxConnection.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxConnectionActionPerformed(evt);
            }
        });

        jPanelStep1.add(jComboBoxConnection);
        jComboBoxConnection.setBounds(0, 90, 220, 22);

        jLabel12.setText("Connection / Datasource");
        jPanelStep1.add(jLabel12);
        jLabel12.setBounds(0, 74, 220, 14);

        jButtonNewConnection.setText("New");
        jButtonNewConnection.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNewConnectionActionPerformed(evt);
            }
        });

        jPanelStep1.add(jButtonNewConnection);
        jButtonNewConnection.setBounds(224, 90, 53, 23);

        jTextFieldBean.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldBeanActionPerformed(evt);
            }
        });

        jPanelStep1.add(jTextFieldBean);
        jTextFieldBean.setBounds(0, 150, 300, 19);

        jButtonLoadQuery.setIcon(new javax.swing.ImageIcon(getClass().getResource("/it/businesslogic/ireport/icons/menu/folder_database.png")));
        jButtonLoadQuery.setText("Load query");
        jButtonLoadQuery.setMargin(new java.awt.Insets(2, 4, 2, 4));
        jButtonLoadQuery.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonLoadQueryActionPerformed1(evt);
            }
        });

        jPanelStep1.add(jButtonLoadQuery);
        jButtonLoadQuery.setBounds(126, 252, 87, 25);

        jButtonSaveQuery.setIcon(new javax.swing.ImageIcon(getClass().getResource("/it/businesslogic/ireport/icons/menu/database_save.png")));
        jButtonSaveQuery.setText("Save query");
        jButtonSaveQuery.setMargin(new java.awt.Insets(2, 4, 2, 4));
        jButtonSaveQuery.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSaveQueryActionPerformed1(evt);
            }
        });

        jPanelStep1.add(jButtonSaveQuery);
        jButtonSaveQuery.setBounds(216, 252, 87, 25);

        jPanelRoot.add(jPanelStep1, java.awt.BorderLayout.CENTER);

        jPanelStep3.setLayout(null);

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel6.setText("Step3: group by...");
        jPanelStep3.add(jLabel6);
        jLabel6.setBounds(0, 10, 298, 16);

        jSeparator5.setBackground(new java.awt.Color(204, 204, 204));
        jSeparator5.setForeground(new java.awt.Color(0, 0, 0));
        jSeparator5.setMaximumSize(new java.awt.Dimension(32767, 1));
        jSeparator5.setMinimumSize(new java.awt.Dimension(98, 1));
        jSeparator5.setPreferredSize(new java.awt.Dimension(10, 1));
        jPanelStep3.add(jSeparator5);
        jSeparator5.setBounds(0, 28, 300, 2);

        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jPanelStep3.add(jComboBox1);
        jComboBox1.setBounds(6, 102, 290, 22);

        jLabelG1.setText("Group 1");
        jPanelStep3.add(jLabelG1);
        jLabelG1.setBounds(6, 84, 110, 16);

        jLabelG2.setText("Group 2");
        jPanelStep3.add(jLabelG2);
        jLabelG2.setBounds(6, 128, 110, 16);

        jComboBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox2ActionPerformed(evt);
            }
        });

        jPanelStep3.add(jComboBox2);
        jComboBox2.setBounds(6, 146, 290, 22);

        jLabelG3.setText("Group 3");
        jPanelStep3.add(jLabelG3);
        jLabelG3.setBounds(6, 172, 110, 16);

        jComboBox3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox3ActionPerformed(evt);
            }
        });

        jPanelStep3.add(jComboBox3);
        jComboBox3.setBounds(6, 190, 290, 22);

        jLabelG4.setText("Group 4");
        jPanelStep3.add(jLabelG4);
        jLabelG4.setBounds(6, 216, 110, 16);

        jPanelStep3.add(jComboBox4);
        jComboBox4.setBounds(6, 234, 290, 22);

        jPanelRoot.add(jPanelStep3, java.awt.BorderLayout.CENTER);

        jPanelStep5.setLayout(null);

        jLabel9.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel9.setText("Step 5: finish");
        jPanelStep5.add(jLabel9);
        jLabel9.setBounds(0, 10, 298, 16);

        jSeparator7.setBackground(new java.awt.Color(204, 204, 204));
        jSeparator7.setForeground(new java.awt.Color(0, 0, 0));
        jSeparator7.setMaximumSize(new java.awt.Dimension(32767, 1));
        jSeparator7.setMinimumSize(new java.awt.Dimension(98, 1));
        jSeparator7.setPreferredSize(new java.awt.Dimension(10, 1));
        jPanelStep5.add(jSeparator7);
        jSeparator7.setBounds(0, 28, 324, 2);

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel4.setText("Congratulation!");
        jPanelStep5.add(jLabel4);
        jLabel4.setBounds(62, 58, 154, 32);

        jLabel10.setText("You have succesfully created a new report.");
        jLabel10.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        jPanelStep5.add(jLabel10);
        jLabel10.setBounds(62, 92, 240, 22);

        jLabel11.setText("Press 'Finish' to generate it.");
        jLabel11.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        jPanelStep5.add(jLabel11);
        jLabel11.setBounds(62, 106, 240, 22);

        jPanelRoot.add(jPanelStep5, java.awt.BorderLayout.CENTER);

        jPanelStep2.setLayout(null);

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel5.setText("Step2: select fields");
        jPanelStep2.add(jLabel5);
        jLabel5.setBounds(0, 10, 300, 16);

        jSeparator4.setBackground(new java.awt.Color(204, 204, 204));
        jSeparator4.setForeground(new java.awt.Color(0, 0, 0));
        jSeparator4.setMaximumSize(new java.awt.Dimension(32767, 1));
        jSeparator4.setMinimumSize(new java.awt.Dimension(98, 1));
        jSeparator4.setPreferredSize(new java.awt.Dimension(10, 1));
        jPanelStep2.add(jSeparator4);
        jSeparator4.setBounds(0, 28, 322, 4);

        jScrollPane1.setViewportView(jList2);

        jPanelStep2.add(jScrollPane1);
        jScrollPane1.setBounds(180, 48, 144, 228);

        jScrollPane2.setViewportView(jList1);

        jPanelStep2.add(jScrollPane2);
        jScrollPane2.setBounds(2, 48, 144, 228);

        jButton4.setFont(new java.awt.Font("Tahoma", 1, 14));
        jButton4.setText(">");
        jButton4.setMargin(new java.awt.Insets(2, 0, 2, 0));
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jPanelStep2.add(jButton4);
        jButton4.setBounds(149, 88, 28, 25);

        jButton5.setFont(new java.awt.Font("Tahoma", 1, 14));
        jButton5.setText(">>");
        jButton5.setMargin(new java.awt.Insets(2, 0, 2, 0));
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jPanelStep2.add(jButton5);
        jButton5.setBounds(149, 118, 28, 25);

        jButton6.setFont(new java.awt.Font("Tahoma", 1, 14));
        jButton6.setText("<");
        jButton6.setMargin(new java.awt.Insets(2, 0, 2, 0));
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jPanelStep2.add(jButton6);
        jButton6.setBounds(149, 154, 28, 25);

        jButton7.setFont(new java.awt.Font("Tahoma", 1, 14));
        jButton7.setText("<<");
        jButton7.setMargin(new java.awt.Insets(2, 0, 2, 0));
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });

        jPanelStep2.add(jButton7);
        jButton7.setBounds(149, 184, 28, 25);

        jPanelRoot.add(jPanelStep2, java.awt.BorderLayout.CENTER);

        jPanelStep4.setLayout(null);

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel8.setText("Step 4: choose layout");
        jPanelStep4.add(jLabel8);
        jLabel8.setBounds(0, 10, 298, 16);

        jSeparator6.setBackground(new java.awt.Color(204, 204, 204));
        jSeparator6.setForeground(new java.awt.Color(0, 0, 0));
        jSeparator6.setMaximumSize(new java.awt.Dimension(32767, 1));
        jSeparator6.setMinimumSize(new java.awt.Dimension(98, 1));
        jSeparator6.setPreferredSize(new java.awt.Dimension(10, 1));
        jPanelStep4.add(jSeparator6);
        jSeparator6.setBounds(0, 28, 320, 2);

        jList3.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jList3.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jList3ValueChanged(evt);
            }
        });

        jScrollPane3.setViewportView(jList3);

        jPanelStep4.add(jScrollPane3);
        jScrollPane3.setBounds(8, 118, 144, 156);

        jPanelStep4.add(jLabelImage);
        jLabelImage.setBounds(156, 118, 166, 158);

        buttonGroup1.add(jRadioButtonColumnarLayout);
        jRadioButtonColumnarLayout.setSelected(true);
        jRadioButtonColumnarLayout.setText("Columnar layout");
        jRadioButtonColumnarLayout.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        jRadioButtonColumnarLayout.setMargin(new java.awt.Insets(0, 0, 0, 0));
        jRadioButtonColumnarLayout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonColumnarLayoutActionPerformed(evt);
            }
        });

        jPanelStep4.add(jRadioButtonColumnarLayout);
        jRadioButtonColumnarLayout.setBounds(10, 70, 160, 15);

        buttonGroup1.add(jRadioButtonTabularLayout);
        jRadioButtonTabularLayout.setText("Tabular layout");
        jRadioButtonTabularLayout.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        jRadioButtonTabularLayout.setMargin(new java.awt.Insets(0, 0, 0, 0));
        jRadioButtonTabularLayout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonTabularLayoutActionPerformed(evt);
            }
        });

        jPanelStep4.add(jRadioButtonTabularLayout);
        jRadioButtonTabularLayout.setBounds(10, 90, 160, 15);

        jPanelRoot.add(jPanelStep4, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanelRoot);
        jPanelRoot.setBounds(138, 0, 324, 278);

        I18n.addOnLanguageChangedListener( this );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonSaveQueryActionPerformed1(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveQueryActionPerformed1
        Misc.saveSQLQuery( jRSQLExpressionArea1.getText(), this );
    }//GEN-LAST:event_jButtonSaveQueryActionPerformed1

    private void jButtonLoadQueryActionPerformed1(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLoadQueryActionPerformed1
        String query = Misc.loadSQLQuery(this);

        if (query != null) {
            jRSQLExpressionArea1.setText(query);
        }
    }//GEN-LAST:event_jButtonLoadQueryActionPerformed1

    private void jTextFieldBeanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldBeanActionPerformed
        jComboBoxConnectionActionPerformed(null);
    }//GEN-LAST:event_jTextFieldBeanActionPerformed

    private void jButtonNewConnectionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNewConnectionActionPerformed


        ConnectionDialog cd = new ConnectionDialog(this,true);

        cd.setVisible(true);

        IReportConnection con = null;
        if (cd.getDialogResult() == JOptionPane.OK_OPTION) {
            con = cd.getIReportConnection();
            MainFrame.getMainInstance().getConnections().addElement(con);

            if (MainFrame.getMainInstance().getConnections().size() == 1) {
                MainFrame.getMainInstance().setActiveConnection(con);
            } else {
                MainFrame.getMainInstance().saveiReportConfiguration();
            }

            this.updateConnections();
            this.jComboBoxConnection.setSelectedItem(con);
        }



    }//GEN-LAST:event_jButtonNewConnectionActionPerformed

    private void jComboBoxConnectionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxConnectionActionPerformed

        boolean canNext = false;
        if (jComboBoxConnection.getSelectedItem() != null) {
            IReportConnection irc = (IReportConnection)jComboBoxConnection.getSelectedItem();

            if (irc.isJDBCConnection()) {
                //jLabel2.setText("SQL query");
                jLabel2.setText(it.businesslogic.ireport.util.I18n.getString("sqlQuery","SQL query"));
                jPanel1.setVisible(true);
                jButtonLoadQuery.setVisible(true);
                jButtonSaveQuery.setVisible(true);
                jTextFieldBean.setVisible(false);

                if (jRSQLExpressionArea1.getText().length() > 0) canNext = true;
            } else if (irc instanceof JRHibernateConnection) {
                //jLabel2.setText("HQL query");
                jLabel2.setText(it.businesslogic.ireport.util.I18n.getString("hqlQuery","HQL query"));
                jPanel1.setVisible(true);
                jButtonLoadQuery.setVisible(true);
                jButtonSaveQuery.setVisible(true);
                jTextFieldBean.setVisible(false);
                if (jRSQLExpressionArea1.getText().length() > 0) canNext = true;
            } else if (irc instanceof it.businesslogic.ireport.connection.JRDataSourceProviderConnection) {
                jLabel2.setText("");
                jPanel1.setVisible(false);
                jButtonLoadQuery.setVisible(false);
                jButtonSaveQuery.setVisible(false);
                jTextFieldBean.setVisible(false);
                canNext = true;
            } else if (irc instanceof it.businesslogic.ireport.connection.JavaBeanDataSourceConnection) {
                jLabel2.setText("JavaBean class");
                jPanel1.setVisible(false);
                jButtonLoadQuery.setVisible(false);
                jButtonSaveQuery.setVisible(false);
                jTextFieldBean.setVisible(true);
                if (jTextFieldBean.getText().length() > 0) canNext = true;
            } else if (irc instanceof it.businesslogic.ireport.connection.JRCSVDataSourceConnection) {
                jLabel2.setText("");
                jPanel1.setVisible(false);
                jButtonLoadQuery.setVisible(false);
                jButtonSaveQuery.setVisible(false);
                jTextFieldBean.setVisible(false);
                canNext = true;
            } else {
                jLabel2.setText("You can't use the wizard with this kind of datasource");
                jPanel1.setVisible(false);
                jButtonLoadQuery.setVisible(false);
                jButtonSaveQuery.setVisible(false);
                jTextFieldBean.setVisible(false);
                canNext = false;
            }
        } else {
            jLabel2.setText("Please create a new connection / datasource.");
            jPanel1.setVisible(false);
            jButtonLoadQuery.setVisible(false);
            jButtonSaveQuery.setVisible(false);
            jTextFieldBean.setVisible(false);
        }

        jButtonNext.setEnabled(canNext);

    }//GEN-LAST:event_jComboBoxConnectionActionPerformed


    private void jRadioButtonColumnarLayoutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonColumnarLayoutActionPerformed
        updateTemplatesList();
    }//GEN-LAST:event_jRadioButtonColumnarLayoutActionPerformed

    private void jRadioButtonTabularLayoutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonTabularLayoutActionPerformed
        updateTemplatesList();
    }//GEN-LAST:event_jRadioButtonTabularLayoutActionPerformed

    private void jList3ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList3ValueChanged

        if (jList3.getSelectedIndex() >= 0) {
            IReportTemplate tf = (IReportTemplate)jList3.getSelectedValue();
            // Take the image...

            this.jLabelImage.setIcon( tf.getIcon() );

            this.jLabelImage.updateUI();
            this.jButtonNext.setEnabled(true);
        } else {
            this.jLabelImage.setIcon( null );
            this.jButtonNext.setEnabled(false);
        }
    }//GEN-LAST:event_jList3ValueChanged

    private void jComboBox3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox3ActionPerformed
        // Add to combobox 2 all not selected items...
        Object obj1 = jComboBox1.getSelectedItem();
        Object obj2 = jComboBox2.getSelectedItem();
        Object obj3 = jComboBox3.getSelectedItem();
        if (jComboBox3.getSelectedIndex() <= 0) {
            disableGroups( 4 );
        } else {
            jComboBox4.setEnabled(true);
            jLabelG4.setEnabled(true);
            javax.swing.DefaultListModel dlm = (javax.swing.DefaultListModel)jList2.getModel();
            jComboBox4.addItem("");
            for (int i=0; i<dlm.getSize(); ++i) {
                Object obj = dlm.getElementAt(i);
                if (obj != obj1 && obj != obj2 && obj != obj3)
                    jComboBox4.addItem( obj );
            }
        }
    }//GEN-LAST:event_jComboBox3ActionPerformed

    private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox2ActionPerformed
        // Add to combobox 2 all not selected items...
        Object obj1 = jComboBox1.getSelectedItem();
        Object obj2 = jComboBox2.getSelectedItem();
        if (jComboBox2.getSelectedIndex() <= 0) {
            disableGroups( 3 );
        } else {
            disableGroups( 4 );
            jComboBox3.setEnabled(true);
            jLabelG3.setEnabled(true);
            javax.swing.DefaultListModel dlm = (javax.swing.DefaultListModel)jList2.getModel();
            jComboBox3.addItem("");
            for (int i=0; i<dlm.getSize(); ++i) {
                Object obj = dlm.getElementAt(i);
                if (obj != obj1 && obj != obj2)
                    jComboBox3.addItem( obj );
            }
        }
    }//GEN-LAST:event_jComboBox2ActionPerformed

    public void disableGroups(int fromIndex) {
        switch (fromIndex) {
            case 2:
                jComboBox2.removeAllItems();
                jComboBox2.setEnabled(false);
                jLabelG2.setEnabled(false);
            case 3:
                jComboBox3.removeAllItems();
                jComboBox3.setEnabled(false);
                jLabelG3.setEnabled(false);
            case 4:
                jComboBox4.removeAllItems();
                jComboBox4.setEnabled(false);
                jLabelG4.setEnabled(false);
        }
    }


    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed

        // Add to combobox 2 all not selected items...
        Object obj1 = jComboBox1.getSelectedItem();
        if (jComboBox1.getSelectedIndex() <= 0) {
            disableGroups( 2 );
        } else {
            disableGroups( 3 );
            jComboBox2.setEnabled(true);
            jLabelG2.setEnabled(true);
            javax.swing.DefaultListModel dlm = (javax.swing.DefaultListModel)jList2.getModel();
            jComboBox2.addItem("");
            for (int i=0; i<dlm.getSize(); ++i) {
                Object obj = dlm.getElementAt(i);
                if (obj != obj1)
                    jComboBox2.addItem( obj );
            }
        }


    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed

        javax.swing.DefaultListModel list1 = (javax.swing.DefaultListModel)jList1.getModel();
        javax.swing.DefaultListModel list2 = (javax.swing.DefaultListModel)jList2.getModel();

        for (int i=0; i< list1.getSize(); ++i) {
            list2.addElement(list1.getElementAt(i));
        }
        list1.removeAllElements();
        if (  ((javax.swing.DefaultListModel)jList2.getModel()).getSize() == 0 )
            jButtonNext.setEnabled(false);
        else
            jButtonNext.setEnabled(true);
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        int index = jList2.getSelectedIndex();
        if (index <0) return;

        Object[] objs = jList2.getSelectedValues();
        for (int i=0; i< objs.length; ++i) {
            Object obj = objs[i];
            //Object obj = jList2.getSelectedValue();
            ((javax.swing.DefaultListModel)jList1.getModel()).addElement(obj);
            jButtonNext.setEnabled(true);
            ((javax.swing.DefaultListModel)jList2.getModel()).removeElement(obj);
            /*
            if ( index < ((javax.swing.DefaultListModel)jList2.getModel()).getSize() )
                jList2.setSelectedIndex(index);
            else if (index-1 >= 0)
            {
                jList2.setSelectedIndex(index-1);
            }
             */
            if (  ((javax.swing.DefaultListModel)jList2.getModel()).getSize() == 0 )
                jButtonNext.setEnabled(false);
            else
                jButtonNext.setEnabled(true);
        }
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed

        int index = jList1.getSelectedIndex();
        if (index <0) return;

        Object[] objs = jList1.getSelectedValues();
        for (int i=0; i< objs.length; ++i) {
            Object obj = objs[i];
            ((javax.swing.DefaultListModel)jList2.getModel()).addElement(obj);
            jButtonNext.setEnabled(true);
            ((javax.swing.DefaultListModel)jList1.getModel()).removeElement(obj);
            /*
            if ( index < ((javax.swing.DefaultListModel)jList1.getModel()).getSize() )
                jList1.setSelectedIndex(index);
            else if (index-1 >= 0)
            {
                jList1.setSelectedIndex(index-1);
            }
             */
            if (  ((javax.swing.DefaultListModel)jList2.getModel()).getSize() == 0 )
                jButtonNext.setEnabled(false);
            else
                jButtonNext.setEnabled(true);
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed

        if (t != null && t.isAlive()) {
            t.interrupt();
        }

        if (wzStep == 5) {
            //javax.swing.JOptionPane.showMessageDialog(null, ((TemplateFile)jList3.getSelectedValue()).file.getAbsolutePath()+"" );
            try {
                Report report = null;
                if (jRadioButtonColumnarLayout.isSelected()) {
                    report = createColumnarReport( ((IReportTemplate)jList3.getSelectedValue()).getXmlFile() );
                } else {
                    report = createTabularReport( ((IReportTemplate)jList3.getSelectedValue()).getXmlFile() );
                }
                this.setReport(report);
                MainFrame.getMainInstance().setActiveConnection( (IReportConnection)jComboBoxConnection.getSelectedItem());
                this.setDialogResult(javax.swing.JOptionPane.OK_OPTION);
            } catch (Exception ex) {
                java.io.StringWriter sw = new java.io.StringWriter();
                ex.printStackTrace(new java.io.PrintWriter( sw ));
                javax.swing.JOptionPane.showMessageDialog(getParent(),sw.getBuffer()+"","Wizard Error", javax.swing.JOptionPane.ERROR_MESSAGE);
                return;
            }

        } else
            this.setDialogResult(javax.swing.JOptionPane.CANCEL_OPTION);

        this.setVisible(false);
        this.dispose();

    }//GEN-LAST:event_jButtonCancelActionPerformed

    private void jButtonNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNextActionPerformed
        this.nextStep();
    }//GEN-LAST:event_jButtonNextActionPerformed

    private void jButtonPrevActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPrevActionPerformed
        this.prevStep();
    }//GEN-LAST:event_jButtonPrevActionPerformed

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
        javax.swing.DefaultListModel list2 = (javax.swing.DefaultListModel)jList1.getModel();
        javax.swing.DefaultListModel list1 = (javax.swing.DefaultListModel)jList2.getModel();

        for (int i=0; i< list1.getSize(); ++i) {
            list2.addElement(list1.getElementAt(i));
        }
        list1.removeAllElements();
        if (  ((javax.swing.DefaultListModel)jList2.getModel()).getSize() == 0 )
            jButtonNext.setEnabled(false);
        else
            jButtonNext.setEnabled(true);
    }//GEN-LAST:event_jButton7ActionPerformed

    /** 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 WizardDialog(new javax.swing.JFrame(), true).setVisible(true);
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JButton jButtonLoadQuery;
    private javax.swing.JButton jButtonNewConnection;
    private javax.swing.JButton jButtonNext;
    private javax.swing.JButton jButtonPrev;
    private javax.swing.JButton jButtonSaveQuery;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JComboBox jComboBox3;
    private javax.swing.JComboBox jComboBox4;
    private javax.swing.JComboBox jComboBoxConnection;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    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 jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLabel jLabelG1;
    private javax.swing.JLabel jLabelG2;
    private javax.swing.JLabel jLabelG3;
    private javax.swing.JLabel jLabelG4;
    private javax.swing.JLabel jLabelImage;
    private javax.swing.JLabel jLabelStep1;
    private javax.swing.JLabel jLabelStep2;
    private javax.swing.JLabel jLabelStep3;
    private javax.swing.JLabel jLabelStep4;
    private javax.swing.JLabel jLabelStep5;
    private javax.swing.JList jList1;
    private javax.swing.JList jList2;
    private javax.swing.JList jList3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanelRoot;
    private javax.swing.JPanel jPanelStep1;
    private javax.swing.JPanel jPanelStep2;
    private javax.swing.JPanel jPanelStep3;
    private javax.swing.JPanel jPanelStep4;
    private javax.swing.JPanel jPanelStep5;
    private javax.swing.JRadioButton jRadioButtonColumnarLayout;
    private javax.swing.JRadioButton jRadioButtonTabularLayout;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JSeparator jSeparator4;
    private javax.swing.JSeparator jSeparator5;
    private javax.swing.JSeparator jSeparator6;
    private javax.swing.JSeparator jSeparator7;
    private javax.swing.JTextField jTextFieldBean;
    // End of variables declaration//GEN-END:variables

    private int status;

    private Report report;

    private int dialogResult;

    public void nextStep() {
        this.setStep( wzStep+1, wzStep);
    }

    public void prevStep() {
        this.setStep(wzStep-1, wzStep);
    }


    public void setStep(int step, int oldStep) {
        jButtonCancel.setText("Cancel");
        switch (step) {
            case 1:
                setViewedPanel(1);
                if (jRSQLExpressionArea1.getText().trim().length() > 0) {
                    jButtonNext.setEnabled(true);
                } else
                    jButtonNext.setEnabled(false);

                jButtonPrev.setEnabled(false);
                break;
            case 2:
                // Read fields....
                if (oldStep < step) {
                    // We must retrive fields...
                    jButtonNext.setEnabled(false);
                    t = new Thread(this);
                    t.start();
                    return;
                }
                setViewedPanel(2);

                if (  ((javax.swing.DefaultListModel)jList2.getModel()).getSize() == 0 )
                    jButtonNext.setEnabled(false);
                else
                    jButtonNext.setEnabled(true);

                jButtonPrev.setEnabled(true);
                break;
            case 3:
                if (oldStep < step) {
                    jComboBox1.removeAllItems();
                    jComboBox2.removeAllItems();
                    jComboBox2.setEnabled(false);
                    jLabelG2.setEnabled(false);
                    jComboBox3.removeAllItems();
                    jComboBox3.setEnabled(false);
                    jLabelG3.setEnabled(false);
                    jComboBox4.removeAllItems();
                    jComboBox4.setEnabled(false);
                    jLabelG4.setEnabled(false);

                    javax.swing.DefaultListModel dlm = (javax.swing.DefaultListModel)jList2.getModel();
                    jComboBox1.addItem("");
                    for (int i=0; i<dlm.getSize(); ++i) {
                        jComboBox1.addItem( dlm.getElementAt(i));
                    }
                }
                setViewedPanel(3);
                break;
            case 4:

                jButtonNext.setEnabled( jList3.getSelectedIndex()>=0 );
                setViewedPanel(4);
                break;
            case 5:
                jButtonNext.setEnabled( false );
                jButtonCancel.setText(it.businesslogic.ireport.util.I18n.getString("finish", "Finish"));
                setViewedPanel(5);
                break;
        }

        wzStep = step;
    }

    public void setViewedPanel(int panel) {
        this.jPanelRoot.removeAll();
        java.awt.Font f = new java.awt.Font( jLabelStep1.getFont().getName(), java.awt.Font.PLAIN, 11);
        java.awt.Font f2 = new java.awt.Font( jLabelStep1.getFont().getName(), java.awt.Font.BOLD, 11);
        this.jLabelStep1.setFont(f);
        this.jLabelStep2.setFont(f);
        this.jLabelStep3.setFont(f);
        this.jLabelStep4.setFont(f);
        this.jLabelStep5.setFont(f);

        switch (panel) {
            case 1:
                this.jPanelRoot.add(jPanelStep1);
                this.jLabelStep1.setFont(f2);
                break;
            case 2:


                this.jPanelRoot.add(jPanelStep2);
                this.jLabelStep2.setFont(f2);
                break;
            case 3:
                this.jPanelRoot.add(jPanelStep3);
                this.jLabelStep3.setFont(f2);
                break;
            case 4:
                this.jPanelRoot.add(jPanelStep4);
                this.jLabelStep4.setFont(f2);
                break;
            case 5:
                this.jPanelRoot.add(jPanelStep5);
                this.jLabelStep5.setFont(f2);
                break;
        }

        jPanelRoot.updateUI();
    }



    /** When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     *
     */
    public void run() {

        Thread.currentThread().setContextClassLoader( MainFrame.getMainInstance().getReportClassLoader() );
        // This method is invoked to read fields....
        try {
            IReportConnection irc = (IReportConnection)jComboBoxConnection.getSelectedItem();


            // Get fields....
            List fields = readFields(irc,jRSQLExpressionArea1.getText(), jTextFieldBean.getText());

            if (fields == null) return;
            DefaultListModel dlm1 = (DefaultListModel)jList1.getModel();
            for (int i=0; i <fields.size(); ++i) {
                it.businesslogic.ireport.JRField field = (JRField)fields.get(i);
                // Check if parameter already exists...
                boolean found = false;
                for (int k=0; k< dlm1.size(); ++k) {
                    it.businesslogic.ireport.JRField f = (it.businesslogic.ireport.JRField)dlm1.getElementAt(k);
                    if (f.getName().equalsIgnoreCase(field.getName())) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    //this.getJReportFrame().getReport().getFields().addElement(field);
                    dlm1.addElement(field);
                }
            }


            setStep(2, 2);

        } catch (Exception ex) {
            java.io.StringWriter sw = new java.io.StringWriter();
            ex.printStackTrace(new java.io.PrintWriter( sw ));
            javax.swing.JOptionPane.showMessageDialog(getParent(),sw.getBuffer()+"","SQL Error", javax.swing.JOptionPane.ERROR_MESSAGE);
            this.cancelElaborationStep1();
            return;
        }


    }

    public void cancelElaborationStep1() {
        this.jButtonNext.setEnabled(true);
        this.jButtonPrev.setEnabled(false);
    }


     /*
      *
      *
      */
    public Report createTabularReport(String templateFileName)
    throws Exception {
        Report template = new Report(templateFileName);

        template.incrementReportChanges();
        template.setFilename(null);

        //2. Find detail and column header bands...
        Band detail=null;
        Band columns=null;

        Enumeration e = template.getBands().elements();
        while (e.hasMoreElements()) {
            Band band = (Band)e.nextElement();
            if (band.getName().equals("detail")) {
                detail = band;
            } else if (band.getName().equals("columnHeader")) {
                columns = band;
            }
        }

        // 1. Normalize position to band...
        e = template.getElements().elements();
        while (e.hasMoreElements()) {
            ReportElement rElement = (ReportElement)e.nextElement();
            rElement.trasform(new java.awt.Point(0,- template.getBandYLocation( rElement.getBand() )),TransformationType.TRANSFORMATION_MOVE );
        }

        //1. Adding groups...
        if (this.jComboBox1.getSelectedIndex() > 0) {
            Group g = template.getGroupByName("Group1");
            Group g1 = new Group( template, ""+jComboBox1.getSelectedItem(),  g.getGroupFooter().getHeight(),g.getGroupHeader().getHeight());
            g1.setGroupExpression("$F{"+ jComboBox1.getSelectedItem() + "}" );
            template.addGroup(g1);

            // Add to g1 all elements attached to g.header and g.footer...
            e = template.getElements().elements();
            while (e.hasMoreElements()) {
                ReportElement rElement = (ReportElement)e.nextElement();
                if (rElement.getBand() == g.getGroupHeader())
                    rElement.setBand(g1.getGroupHeader() );
                else if (rElement.getBand() == g.getGroupFooter())
                    rElement.setBand(g1.getGroupFooter() );
                // Set text to Group1 label...
                if (rElement instanceof StaticTextReportElement) {
                    StaticTextReportElement stre = (StaticTextReportElement)rElement;
                    if (stre.getText().equals("G1Label"))
                        stre.setText( ""+jComboBox1.getSelectedItem());
                } else if (rElement instanceof TextFieldReportElement) {
                    TextFieldReportElement tfre = (TextFieldReportElement)rElement;
                    if (tfre.getText().equals("G1Field")) {
                        tfre.setText("$F{"+jComboBox1.getSelectedItem()+"}");
                        JRField f = (JRField)jComboBox1.getSelectedItem();

                        tfre.setMatchingClassExpression( f.getClassType(), true );
                       }
                }
            }
        }

        if (this.jComboBox2.getSelectedIndex() > 0) {
            Group g = template.getGroupByName("Group2");
            Group g2 = new Group( template, ""+jComboBox2.getSelectedItem(),  g.getGroupFooter().getHeight(),g.getGroupHeader().getHeight());
            g2.setGroupExpression("$F{"+ jComboBox2.getSelectedItem() + "}" );
            template.addGroup(g2);

            // Add to g2 all elements attached to g.header and g.footer...
            e = template.getElements().elements();
            while (e.hasMoreElements()) {
                ReportElement rElement = (ReportElement)e.nextElement();
                if (rElement.getBand() == g.getGroupHeader())
                    rElement.setBand(g2.getGroupHeader() );
                else if (rElement.getBand() == g.getGroupFooter())
                    rElement.setBand(g2.getGroupFooter() );
                // Set text to Group2 label...
                if (rElement instanceof StaticTextReportElement) {
                    StaticTextReportElement stre = (StaticTextReportElement)rElement;
                    if (stre.getText().equals("G2Label"))
                        stre.setText( ""+jComboBox2.getSelectedItem());
                } else if (rElement instanceof TextFieldReportElement) {
                    TextFieldReportElement tfre = (TextFieldReportElement)rElement;
                    if (tfre.getText().equals("G2Field")) {
                        tfre.setText("$F{"+jComboBox2.getSelectedItem()+"}");
                        JRField f = (JRField)jComboBox2.getSelectedItem();
                        tfre.setMatchingClassExpression( f.getClassType(), true );
                    }
                }
            }
        }

        if (this.jComboBox3.getSelectedIndex() > 0) {
            Group g = template.getGroupByName("Group3");
            Group g3 = new Group( template, ""+jComboBox3.getSelectedItem(),  g.getGroupFooter().getHeight(),g.getGroupHeader().getHeight());
            g3.setGroupExpression("$F{"+ jComboBox3.getSelectedItem() + "}" );
            template.addGroup(g3);

            // Add to g3 all elements attached to g.header and g.footer...
            e = template.getElements().elements();
            while (e.hasMoreElements()) {
                ReportElement rElement = (ReportElement)e.nextElement();
                if (rElement.getBand() == g.getGroupHeader())
                    rElement.setBand(g3.getGroupHeader() );
                else if (rElement.getBand() == g.getGroupFooter())
                    rElement.setBand(g3.getGroupFooter() );
                // Set text to Group3 label...
                if (rElement instanceof StaticTextReportElement) {
                    StaticTextReportElement stre = (StaticTextReportElement)rElement;
                    if (stre.getText().equals("G3Label"))
                        stre.setText( ""+jComboBox3.getSelectedItem());
                } else if (rElement instanceof TextFieldReportElement) {
                    TextFieldReportElement tfre = (TextFieldReportElement)rElement;
                    if (tfre.getText().equals("G3Field")) {
                        tfre.setText("$F{"+jComboBox3.getSelectedItem()+"}");
                        JRField f = (JRField)jComboBox3.getSelectedItem();
                        tfre.setMatchingClassExpression( f.getClassType(), true );
                    }
                }
            }
        }

        if (this.jComboBox4.getSelectedIndex() > 0) {
            Group g = template.getGroupByName("Group4");
            Group g4 = new Group( template, ""+jComboBox4.getSelectedItem(),  g.getGroupFooter().getHeight(),g.getGroupHeader().getHeight());
            g4.setGroupExpression("$F{"+ jComboBox4.getSelectedItem() + "}" );
            template.addGroup(g4);

            // Add to g4 all elements attached to g.header and g.footer...
            e = template.getElements().elements();
            while (e.hasMoreElements()) {
                ReportElement rElement = (ReportElement)e.nextElement();
                if (rElement.getBand() == g.getGroupHeader())
                    rElement.setBand(g4.getGroupHeader() );
                else if (rElement.getBand() == g.getGroupFooter())
                    rElement.setBand(g4.getGroupFooter() );
                // Set text to Group4 label...
                if (rElement instanceof StaticTextReportElement) {
                    StaticTextReportElement stre = (StaticTextReportElement)rElement;
                    if (stre.getText().equals("G4Label"))
                        stre.setText( ""+jComboBox4.getSelectedItem());
                } else if (rElement instanceof TextFieldReportElement) {
                    TextFieldReportElement tfre = (TextFieldReportElement)rElement;
                    if (tfre.getText().equals("G4Field")) {
                        tfre.setText("$F{"+jComboBox4.getSelectedItem()+"}");
                        JRField f = (JRField)jComboBox4.getSelectedItem();
                        tfre.setMatchingClassExpression( f.getClassType(), true );
                    }
                }
            }
        }

        //1. Adding fields...
        int currentx = template.getLeftMargin()+10;
        int currenty = 10;
        e = template.getElements().elements();
        StaticTextReportElement detailLabel = null;
        TextFieldReportElement detailField = null;
        while (e.hasMoreElements() && (detailLabel==null || detailField == null) ) {
            ReportElement rElement = (ReportElement)e.nextElement();
            if (rElement instanceof StaticTextReportElement) {
                StaticTextReportElement stre = (StaticTextReportElement)rElement;
                if (stre.getText().equalsIgnoreCase("DetailLabel"))
                    detailLabel =stre;
            } else if (rElement instanceof TextFieldReportElement) {
                TextFieldReportElement tfre = (TextFieldReportElement)rElement;
                if (tfre.getText().equalsIgnoreCase("DetailField"))
                    detailField = tfre;
            }
        }

        if (detailField != null)
            template.getElements().removeElement(detailField);
        if (detailLabel != null)
            template.getElements().removeElement(detailLabel);

        if (detailField == null)
            detailField = new TextFieldReportElement(0,0,100,20);
        if (detailLabel == null)
            detailLabel = new StaticTextReportElement(0,0,100,18);

        int nfields = jList2.getModel().getSize();
        if (jComboBox1.getSelectedIndex()>0) nfields--;
        if (jComboBox2.getSelectedIndex()>0) nfields--;
        if (jComboBox3.getSelectedIndex()>0) nfields--;
        if (jComboBox4.getSelectedIndex()>0) nfields--;

        int fwidth = template.getColumnWidth()/nfields;

        for (int i=0; i<jList2.getModel().getSize(); ++i) {
            // FIELD
            it.businesslogic.ireport.JRField f = (it.businesslogic.ireport.JRField)jList2.getModel().getElementAt(i);
            template.addField(f);

            if (jComboBox1.getSelectedIndex()>0 && f.getName().equalsIgnoreCase( ""+jComboBox1.getSelectedItem() ))
                continue;
            if (jComboBox2.getSelectedIndex()>0 && f.getName().equalsIgnoreCase( ""+jComboBox2.getSelectedItem() ))
                continue;
            if (jComboBox3.getSelectedIndex()>0 && f.getName().equalsIgnoreCase( ""+jComboBox3.getSelectedItem() ))
                continue;
            if (jComboBox4.getSelectedIndex()>0 && f.getName().equalsIgnoreCase( ""+jComboBox4.getSelectedItem() ))
                continue;


            TextFieldReportElement re = (TextFieldReportElement)detailField.cloneMe();
            re.setPosition(new java.awt.Point(currentx,detailField.getPosition().y));
            re.setWidth( fwidth);
            re.updateBounds();
            re.setText("$F{"+ f.getName() +"}");

            re.setBand(detail);
            re.setMatchingClassExpression( f.getClassType(), true );
            template.getElements().addElement(re);

            // COLUMN LABEL...
            StaticTextReportElement sre = (StaticTextReportElement)detailLabel.cloneMe();
            sre.setPosition(new java.awt.Point(currentx,detailLabel.getPosition().y));
            sre.setWidth(fwidth);
            sre.updateBounds();
            sre.setText(""+ f.getName() +"");
            sre.setBand(columns);
            template.getElements().addElement(sre);

            currentx += fwidth;
            currentx = Math.min(template.getWidth() - template.getRightMargin()+10-30, currentx);
        }

        // Remove template groups...****************
        e = template.getElements().elements();
        Vector elements_to_delete = new Vector();
        while (e.hasMoreElements()) {
            ReportElement rElement = (ReportElement)e.nextElement();
            Group g = null;
            if ((g=template.getGroupByName("Group1"))!=null && (rElement.getBand() == g.getGroupHeader() || rElement.getBand() == g.getGroupFooter()))
                elements_to_delete.addElement(rElement);
            else if ((g=template.getGroupByName("Group2"))!=null && (rElement.getBand() == g.getGroupHeader() || rElement.getBand() == g.getGroupFooter()))
                elements_to_delete.addElement(rElement);
            else if ((g=template.getGroupByName("Group3"))!=null && (rElement.getBand() == g.getGroupHeader() || rElement.getBand() == g.getGroupFooter()))
                elements_to_delete.addElement(rElement);
            else if ((g=template.getGroupByName("Group4"))!=null && (rElement.getBand() == g.getGroupHeader() || rElement.getBand() == g.getGroupFooter()))
                elements_to_delete.addElement(rElement);
        }
        e =elements_to_delete.elements();
        while (e.hasMoreElements()) {
            template.getElements().removeElement(e.nextElement());
        }

        Group g;
        if ((g=template.getGroupByName("Group1"))!=null) {
            template.getBands().removeElement(g.getGroupFooter());
            template.getBands().removeElement(g.getGroupHeader());
            template.getGroups().removeElement(g);
        }
        if ((g=template.getGroupByName("Group2"))!=null) {
            template.getBands().removeElement(g.getGroupFooter());
            template.getBands().removeElement(g.getGroupHeader());
            template.getGroups().removeElement(g);
        }
        if ((g=template.getGroupByName("Group3"))!=null) {
            template.getBands().removeElement(g.getGroupFooter());
            template.getBands().removeElement(g.getGroupHeader());
            template.getGroups().removeElement(g);
        }

        if ((g=template.getGroupByName("Group4"))!=null) {
            template.getBands().removeElement(g.getGroupFooter());
            template.getBands().removeElement(g.getGroupHeader());
            template.getGroups().removeElement(g);
        }

        // Positioning columns band...
        /*
        if ((g=template.getGroupByName("Columns"))!=null)
        {
                template.getGroups().removeElement(g);
                template.getBands().removeElement(g.getGroupHeader());
                template.getBands().removeElement(g.getGroupFooter());
                template.addGroup(g);
                // we must adjust band position...
        }
         */
        // Adjust vertical position of elements
        e = template.getElements().elements();
        while (e.hasMoreElements()) {
            ReportElement rElement = (ReportElement)e.nextElement();
            rElement.trasform(new java.awt.Point(0,+ template.getBandYLocation( rElement.getBand() )),TransformationType.TRANSFORMATION_MOVE );
        }

        if (jComboBoxConnection.getSelectedItem() instanceof JDBCConnection)
        {
            template.setQuery( jRSQLExpressionArea1.getText() );

        }
        else if (jComboBoxConnection.getSelectedItem() instanceof JRHibernateConnection)
        {
            template.setQuery( jRSQLExpressionArea1.getText() );
            template.setQueryLanguage("hql");
        }


        return template;
    }

    /**********************************************************
     *
     */
    public Report createColumnarReport(String templateFileName)
    throws Exception {
        Report template = new Report(templateFileName);

        template.incrementReportChanges();
        template.setFilename(null);

        //2. Find detail and column header bands...
        Band detail=null;
        Band columns=null;

        Enumeration e = template.getBands().elements();
        while (e.hasMoreElements()) {
            Band band = (Band)e.nextElement();
            if (band.getName().equals("detail")) {
                detail = band;
            } else if (band.getName().equals("columnHeader")) {
                columns = band;
            }
        }

        // 1. Normalize position to band...
        e = template.getElements().elements();
        while (e.hasMoreElements()) {
            ReportElement rElement = (ReportElement)e.nextElement();
            rElement.trasform(new java.awt.Point(0,- template.getBandYLocation( rElement.getBand() )),TransformationType.TRANSFORMATION_MOVE );
        }

        //1. Adding groups...
        if (this.jComboBox1.getSelectedIndex() > 0) {
            Group g = template.getGroupByName("Group1");
            Group g1 = new Group( template, ""+jComboBox1.getSelectedItem(),  g.getGroupFooter().getHeight(),g.getGroupHeader().getHeight());
            g1.setGroupExpression("$F{"+ jComboBox1.getSelectedItem() + "}" );
            template.addGroup(g1);

            // Add to g1 all elements attached to g.header and g.footer...
            e = template.getElements().elements();
            while (e.hasMoreElements()) {
                ReportElement rElement = (ReportElement)e.nextElement();
                if (rElement.getBand() == g.getGroupHeader())
                    rElement.setBand(g1.getGroupHeader() );
                else if (rElement.getBand() == g.getGroupFooter())
                    rElement.setBand(g1.getGroupFooter() );
                // Set text to Group1 label...
                if (rElement instanceof StaticTextReportElement) {
                    StaticTextReportElement stre = (StaticTextReportElement)rElement;
                    if (stre.getText().equals("G1Label"))
                        stre.setText( ""+jComboBox1.getSelectedItem());
                } else if (rElement instanceof TextFieldReportElement) {
                    TextFieldReportElement tfre = (TextFieldReportElement)rElement;
                    if (tfre.getText().equals("G1Field")) {
                        tfre.setText("$F{"+jComboBox1.getSelectedItem()+"}");
                        JRField f = (JRField)jComboBox1.getSelectedItem();
                        tfre.setMatchingClassExpression( f.getClassType(), true );
                    }
                }
            }
        }

        if (this.jComboBox2.getSelectedIndex() > 0) {
            Group g = template.getGroupByName("Group2");
            Group g2 = new Group( template, ""+jComboBox2.getSelectedItem(),  g.getGroupFooter().getHeight(),g.getGroupHeader().getHeight());
            g2.setGroupExpression("$F{"+ jComboBox2.getSelectedItem() + "}" );
            template.addGroup(g2);

            // Add to g2 all elements attached to g.header and g.footer...
            e = template.getElements().elements();
            while (e.hasMoreElements()) {
                ReportElement rElement = (ReportElement)e.nextElement();
                if (rElement.getBand() == g.getGroupHeader())
                    rElement.setBand(g2.getGroupHeader() );
                else if (rElement.getBand() == g.getGroupFooter())
                    rElement.setBand(g2.getGroupFooter() );
                // Set text to Group2 label...
                if (rElement instanceof StaticTextReportElement) {
                    StaticTextReportElement stre = (StaticTextReportElement)rElement;
                    if (stre.getText().equals("G2Label"))
                        stre.setText( ""+jComboBox2.getSelectedItem());
                } else if (rElement instanceof TextFieldReportElement) {
                    TextFieldReportElement tfre = (TextFieldReportElement)rElement;
                    if (tfre.getText().equals("G2Field")) {
                        tfre.setText("$F{"+jComboBox2.getSelectedItem()+"}");
                        JRField f = (JRField)jComboBox2.getSelectedItem();
                        tfre.setMatchingClassExpression( f.getClassType(), true );
                    }
                }
            }
        }

        if (this.jComboBox3.getSelectedIndex() > 0) {
            Group g = template.getGroupByName("Group3");
            Group g3 = new Group( template, ""+jComboBox3.getSelectedItem(),  g.getGroupFooter().getHeight(),g.getGroupHeader().getHeight());
            g3.setGroupExpression("$F{"+ jComboBox3.getSelectedItem() + "}" );
            template.addGroup(g3);

            // Add to g3 all elements attached to g.header and g.footer...
            e = template.getElements().elements();
            while (e.hasMoreElements()) {
                ReportElement rElement = (ReportElement)e.nextElement();
                if (rElement.getBand() == g.getGroupHeader())
                    rElement.setBand(g3.getGroupHeader() );
                else if (rElement.getBand() == g.getGroupFooter())
                    rElement.setBand(g3.getGroupFooter() );
                // Set text to Group3 label...
                if (rElement instanceof StaticTextReportElement) {
                    StaticTextReportElement stre = (StaticTextReportElement)rElement;
                    if (stre.getText().equals("G3Label"))
                        stre.setText( ""+jComboBox3.getSelectedItem());
                } else if (rElement instanceof TextFieldReportElement) {
                    TextFieldReportElement tfre = (TextFieldReportElement)rElement;
                    if (tfre.getText().equals("G3Field")) {
                        tfre.setText("$F{"+jComboBox3.getSelectedItem()+"}");
                        JRField f = (JRField)jComboBox3.getSelectedItem();
                        tfre.setMatchingClassExpression( f.getClassType(), true );
                    }
                }
            }
        }

        if (this.jComboBox4.getSelectedIndex() > 0) {
            Group g = template.getGroupByName("Group4");
            Group g4 = new Group( template, ""+jComboBox4.getSelectedItem(),  g.getGroupFooter().getHeight(),g.getGroupHeader().getHeight());
            g4.setGroupExpression("$F{"+ jComboBox4.getSelectedItem() + "}" );
            template.addGroup(g4);

            // Add to g4 all elements attached to g.header and g.footer...
            e = template.getElements().elements();
            while (e.hasMoreElements()) {
                ReportElement rElement = (ReportElement)e.nextElement();
                if (rElement.getBand() == g.getGroupHeader())
                    rElement.setBand(g4.getGroupHeader() );
                else if (rElement.getBand() == g.getGroupFooter())
                    rElement.setBand(g4.getGroupFooter() );
                // Set text to Group4 label...
                if (rElement instanceof StaticTextReportElement) {
                    StaticTextReportElement stre = (StaticTextReportElement)rElement;
                    if (stre.getText().equals("G4Label"))
                        stre.setText( ""+jComboBox4.getSelectedItem());
                } else if (rElement instanceof TextFieldReportElement) {
                    TextFieldReportElement tfre = (TextFieldReportElement)rElement;
                    if (tfre.getText().equals("G4Field")) {
                        tfre.setText("$F{"+jComboBox4.getSelectedItem()+"}");
                        JRField f = (JRField)jComboBox4.getSelectedItem();
                        tfre.setMatchingClassExpression( f.getClassType(), true );
                    }
                }
            }
        }

        //1. Adding fields...
        int currentx = template.getLeftMargin()+10;
        int currenty = 10;
        e = template.getElements().elements();
        StaticTextReportElement detailLabel = null;
        TextFieldReportElement detailField = null;
        while (e.hasMoreElements() && (detailLabel==null || detailField == null) ) {
            ReportElement rElement = (ReportElement)e.nextElement();
            if (rElement instanceof StaticTextReportElement) {
                StaticTextReportElement stre = (StaticTextReportElement)rElement;
                if (stre.getText().equalsIgnoreCase("DetailLabel"))
                    detailLabel =stre;
            } else if (rElement instanceof TextFieldReportElement) {
                TextFieldReportElement tfre = (TextFieldReportElement)rElement;
                if (tfre.getText().equalsIgnoreCase("DetailField"))
                    detailField = tfre;
            }
        }

        if (detailField != null)
            template.getElements().removeElement(detailField);
        if (detailLabel != null)
            template.getElements().removeElement(detailLabel);

        if (detailField == null)
            detailField = new TextFieldReportElement(0,0,100,20);
        if (detailLabel == null)
            detailLabel = new StaticTextReportElement(0,0,100,18);

        int nfields = jList2.getModel().getSize();
        if (jComboBox1.getSelectedIndex()>0) nfields--;
        if (jComboBox2.getSelectedIndex()>0) nfields--;
        if (jComboBox3.getSelectedIndex()>0) nfields--;
        if (jComboBox4.getSelectedIndex()>0) nfields--;

        int fwidth = template.getColumnWidth()/nfields;
        int ffheight =  detailField.getPosition().y;

        for (int i=0; i<jList2.getModel().getSize(); ++i) {
            // FIELD
            it.businesslogic.ireport.JRField f = (it.businesslogic.ireport.JRField)jList2.getModel().getElementAt(i);
            template.addField(f);

            if (jComboBox1.getSelectedIndex()>0 && f.getName().equalsIgnoreCase( ""+jComboBox1.getSelectedItem() ))
                continue;
            if (jComboBox2.getSelectedIndex()>0 && f.getName().equalsIgnoreCase( ""+jComboBox2.getSelectedItem() ))
                continue;
            if (jComboBox3.getSelectedIndex()>0 && f.getName().equalsIgnoreCase( ""+jComboBox3.getSelectedItem() ))
                continue;
            if (jComboBox4.getSelectedIndex()>0 && f.getName().equalsIgnoreCase( ""+jComboBox4.getSelectedItem() ))
                continue;


            TextFieldReportElement re = (TextFieldReportElement)detailField.cloneMe();
            re.setPosition(new java.awt.Point(detailField.getPosition().x, ffheight));
            re.updateBounds();
            re.setText("$F{"+ f.getName() +"}");

            re.setBand(detail);
            re.setMatchingClassExpression( f.getClassType(), true );

            template.getElements().addElement(re);

            // COLUMN LABEL...
            StaticTextReportElement sre = (StaticTextReportElement)detailLabel.cloneMe();
            sre.setPosition(new java.awt.Point(detailLabel.getPosition().x,ffheight));
            sre.setWidth(fwidth);
            sre.updateBounds();
            sre.setText(""+ f.getName() +"");
            sre.setBand(detail);
            template.getElements().addElement(sre);

            ffheight +=  detailField.position.y+detailField.height-10;
        }

        detail.setHeight(ffheight);

        // Remove template groups...****************
        e = template.getElements().elements();
        Vector elements_to_delete = new Vector();
        while (e.hasMoreElements()) {
            ReportElement rElement = (ReportElement)e.nextElement();
            Group g = null;
            if ((g=template.getGroupByName("Group1"))!=null && (rElement.getBand() == g.getGroupHeader() || rElement.getBand() == g.getGroupFooter()))
                elements_to_delete.addElement(rElement);
            else if ((g=template.getGroupByName("Group2"))!=null && (rElement.getBand() == g.getGroupHeader() || rElement.getBand() == g.getGroupFooter()))
                elements_to_delete.addElement(rElement);
            else if ((g=template.getGroupByName("Group3"))!=null && (rElement.getBand() == g.getGroupHeader() || rElement.getBand() == g.getGroupFooter()))
                elements_to_delete.addElement(rElement);
            else if ((g=template.getGroupByName("Group4"))!=null && (rElement.getBand() == g.getGroupHeader() || rElement.getBand() == g.getGroupFooter()))
                elements_to_delete.addElement(rElement);
        }
        e =elements_to_delete.elements();
        while (e.hasMoreElements()) {
            template.getElements().removeElement(e.nextElement());
        }

        Group g;
        if ((g=template.getGroupByName("Group1"))!=null) {
            template.getBands().removeElement(g.getGroupFooter());
            template.getBands().removeElement(g.getGroupHeader());
            template.getGroups().removeElement(g);
        }
        if ((g=template.getGroupByName("Group2"))!=null) {
            template.getBands().removeElement(g.getGroupFooter());
            template.getBands().removeElement(g.getGroupHeader());
            template.getGroups().removeElement(g);
        }
        if ((g=template.getGroupByName("Group3"))!=null) {
            template.getBands().removeElement(g.getGroupFooter());
            template.getBands().removeElement(g.getGroupHeader());
            template.getGroups().removeElement(g);
        }

        if ((g=template.getGroupByName("Group4"))!=null) {
            template.getBands().removeElement(g.getGroupFooter());
            template.getBands().removeElement(g.getGroupHeader());
            template.getGroups().removeElement(g);
        }

        // Positioning columns band...
        /*
        if ((g=template.getGroupByName("Columns"))!=null)
        {
                template.getGroups().removeElement(g);
                template.getBands().removeElement(g.getGroupHeader());
                template.getBands().removeElement(g.getGroupFooter());
                template.addGroup(g);
                // we must adjust band position...
        }
         */
        // Adjust vertical position of elements
        e = template.getElements().elements();
        while (e.hasMoreElements()) {
            ReportElement rElement = (ReportElement)e.nextElement();
            rElement.trasform(new java.awt.Point(0,+ template.getBandYLocation( rElement.getBand() )),TransformationType.TRANSFORMATION_MOVE );
        }

        template.setQuery( jRSQLExpressionArea1.getText() );

        return template;
    }


    /** Getter for property dialogResult.
     * @return Value of property dialogResult.
     *
     */
    public int getDialogResult() {
        return dialogResult;
    }

    /** Setter for property dialogResult.
     * @param dialogResult New value of property dialogResult.
     *
     */
    public void setDialogResult(int dialogResult) {
        this.dialogResult = dialogResult;
    }

    /** Getter for property report.
     * @return Value of property report.
     *
     */
    public it.businesslogic.ireport.Report getReport() {
        return report;
    }

    /** Setter for property report.
     * @param report New value of property report.
     *
     */
    public void setReport(it.businesslogic.ireport.Report report) {
        this.report = report;
    }



    /**
     * Return a list of JRField
     *
     */
    public static List readFields(IReportConnection conn, String query, String className) {
        String error_msg = null;
        if (conn.isJDBCConnection()) {
            Connection con = null;
            Statement ps = null;

            try {


                con = conn.getConnection();

                ps = con.createStatement();

                // Some JDBC drivers don't supports this method...
                try { ps.setFetchSize(0); } catch(Exception e ) {}

                ResultSet rs = ps.executeQuery(query);


                ResultSetMetaData rsmd = rs.getMetaData();


                List columns = new ArrayList();
                for (int i=1; i <=rsmd.getColumnCount(); ++i) {
                    it.businesslogic.ireport.JRField field =
                            new it.businesslogic.ireport.JRField(
                            rsmd.getColumnLabel(i),
                            Misc.getJdbcTypeClass(rsmd, i) );
                    columns.add( field );
                }


                return columns;
            } catch( IllegalArgumentException ie ) {
                error_msg = ie.getMessage();
            } catch (NoClassDefFoundError ex) {
                ex.printStackTrace();
                error_msg = "NoClassDefFoundError!!\nCheck your classpath!";
            } catch (java.sql.SQLException ex) {
                error_msg = "SQL problems:\n"+ex.getMessage();
            } catch (Exception ex) {
                ex.printStackTrace();
                error_msg = "General problem:\n"+ex.getMessage()+
                        "\n\nCheck username and password; is the DBMS active ?!";
            } finally {
                if(ps!=null) try { ps.close(); } catch(Exception e ) {}
                if(con !=null) try { con.close(); } catch(Exception e ) {}
            }
        } else if ( conn instanceof JRHibernateConnection) {
            it.businesslogic.ireport.hibernate.HQLFieldsReader reader = new it.businesslogic.ireport.hibernate.HQLFieldsReader(query,new Vector());
            try {
                return reader.readFields();
            } catch (Exception ex) {
                ex.printStackTrace();
                error_msg = "General problem:\n"+ex.getMessage();
            }
        } else if ( conn instanceof JRDataSourceProviderConnection) {

            try {
                net.sf.jasperreports.engine.JRField[] jrfields = ((JRDataSourceProviderConnection)conn).getDataSourceProvider().getFields(null);

                java.util.ArrayList v_fields = new java.util.ArrayList();
                for (int i=0; i<jrfields.length; ++i) {
                    it.businesslogic.ireport.JRField field = new it.businesslogic.ireport.JRField(jrfields[i].getName(), jrfields[i].getValueClassName());
                    field.setDescription( it.businesslogic.ireport.util.Misc.nvl( jrfields[i].getDescription(),""));
                    v_fields.add( field );
                }

                return v_fields;

            } catch (Exception ex) {
                ex.printStackTrace();
                error_msg = "General problem:\n"+ex.getMessage();
            }

        } else if ( conn instanceof JavaBeanDataSourceConnection) {
            java.util.ArrayList v_fields = new java.util.ArrayList();
            try {

                Class clazz = Class.forName(className);

                java.beans.PropertyDescriptor[] pd = org.apache.commons.beanutils.PropertyUtils.getPropertyDescriptors(clazz);
                for (int nd =0; nd < pd.length; ++nd) {
                    String fieldName = pd[nd].getName();
                    if (pd[nd].getPropertyType() != null && pd[nd].getReadMethod() != null) {
                        String returnType =  pd[nd].getPropertyType().getName();
                        it.businesslogic.ireport.JRField field = new it.businesslogic.ireport.JRField(fieldName, Misc.getJRFieldType(returnType));
                        field.setDescription(""); //Field returned by " +methods[i].getName() + " (real type: "+ returnType +")");
                        v_fields.add( field );
                    }
                }
                return v_fields;

            } catch (ClassNotFoundException cnf) {
                error_msg="Class not found!\nCheck your classpath and retry.";
            } catch (Exception ex) {
                ex.printStackTrace();
                error_msg = "Error: " + ex.getMessage();
            }

        } else if ( conn instanceof JRCSVDataSourceConnection) {
            java.util.ArrayList v_fields = new java.util.ArrayList();
            try {

                Vector names = ((JRCSVDataSourceConnection)conn).getColumnNames();

                for (int nd =0; nd < names.size(); ++nd) {
                    String fieldName = ""+names.elementAt(nd);
                    it.businesslogic.ireport.JRField field = new it.businesslogic.ireport.JRField(fieldName, "java.lang.String");
                    field.setDescription(""); //Field returned by " +methods[i].getName() + " (real type: "+ returnType +")");
                    v_fields.add( field );
                }
                return v_fields;

            } catch (Exception ex) {
                ex.printStackTrace();
                error_msg = "Error: " + ex.getMessage();
            }

        }



        if (error_msg != null) {
            JOptionPane.showMessageDialog(MainFrame.getMainInstance(),error_msg,"Error", JOptionPane.ERROR_MESSAGE);
        }

        return null;
    }
    //added by Felix Firgau on Feb 8th 2006
    public void applyI18n(){

      jLabel1.setText(it.businesslogic.ireport.util.I18n.getString("wizLabel", "Steps"));
      jLabelStep1.setText(it.businesslogic.ireport.util.I18n.getString("wizStep1"));/*, "Step 1"));*/
      jLabelStep2.setText(it.businesslogic.ireport.util.I18n.getString("wizStep2", "Step 2"));
      jLabelStep3.setText(it.businesslogic.ireport.util.I18n.getString("wizStep3", "Step 3"));
      jLabelStep4.setText(it.businesslogic.ireport.util.I18n.getString("wizStep4","Step 4"));
      jLabelStep5.setText(it.businesslogic.ireport.util.I18n.getString("wizStep5","Step 5"));
      jLabel3.setText(it.businesslogic.ireport.util.I18n.getString("wizStep1.1","1. Query"));
      jLabel5.setText(it.businesslogic.ireport.util.I18n.getString("wizStep2.1","2. Fields selection"));
      jLabel6.setText(it.businesslogic.ireport.util.I18n.getString("wizStep3.1","3. Group by..."));
      jLabel8.setText(it.businesslogic.ireport.util.I18n.getString("wizStep4.1","4. Layout"));
      jLabel9.setText(it.businesslogic.ireport.util.I18n.getString("wizStep5.1","5. Finish"));
      jLabel2.setText(it.businesslogic.ireport.util.I18n.getString("queryString","Query string"));
      jLabelG1.setText(it.businesslogic.ireport.util.I18n.getString("group","Group")+" 1");
      jLabelG2.setText(it.businesslogic.ireport.util.I18n.getString("group","Group")+" 2");
      jLabelG3.setText(it.businesslogic.ireport.util.I18n.getString("group","Group")+" 3");
      jLabelG4.setText(it.businesslogic.ireport.util.I18n.getString("group","Group")+" 4");
      jLabel4.setText(it.businesslogic.ireport.util.I18n.getString("congratulation","Congratulation!"));
      jLabel10.setText(it.businesslogic.ireport.util.I18n.getString("wizardSuccess","You have succesfully created a new report."));
      jLabel11.setText(it.businesslogic.ireport.util.I18n.getString("wizardFinished","Press 'Finish' to generate it."));
      jButtonPrev.setText(it.businesslogic.ireport.util.I18n.getString("prev","< Prev"));
      jButtonNext.setText(it.businesslogic.ireport.util.I18n.getString("next","Next >"));
      jButtonCancel.setText(it.businesslogic.ireport.util.I18n.getString("cancel","Cancel"));
      jButtonNewConnection.setText(it.businesslogic.ireport.util.I18n.getString("new","New"));
      jButtonLoadQuery.setText(it.businesslogic.ireport.util.I18n.getString("loadQuery","Load query"));
      jButtonSaveQuery.setText(it.businesslogic.ireport.util.I18n.getString("saveQuery","Save query"));
    }

    public void languageChanged(LanguageChangedEvent evt) {
      applyI18n();
    }
    //Modification end

}

class TemplateFile {

    public File file = null;
    public String name = "";
    public String toString() { return name; }
}
