/*
 * Copyright (C) 2005 - 2011 Jaspersoft Corporation. All rights reserved.
 * http://www.jaspersoft.com.
 *
 * Unless you have purchased  a commercial license agreement from Jaspersoft,
 * the following license terms  apply:
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License  as
 * published by the Free Software Foundation, either version 3 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 Affero  General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public  License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.jaspersoft.jasperserver.irplugin.gui.wizard;

import com.jaspersoft.jasperserver.api.metadata.xml.domain.impl.ResourceDescriptor;
import com.jaspersoft.jasperserver.irplugin.IRPlugin;
import com.jaspersoft.jasperserver.irplugin.JServer;
import com.jaspersoft.jasperserver.irplugin.RepositoryJrxmlFile;
import com.jaspersoft.jasperserver.irplugin.RepositoryReportUnit;
import com.jaspersoft.jasperserver.irplugin.gui.DataSourceDialog;
import com.jaspersoft.jasperserver.irplugin.gui.QualityLabel;
import com.jaspersoft.jasperserver.irplugin.gui.RepositoryExplorer;
import com.jaspersoft.jasperserver.irplugin.gui.ValidationUtils;
import com.jaspersoft.jasperserver.irplugin.gui.explorer.ResourceChooser;
import com.jaspersoft.jasperserver.irplugin.gui.jrxmlvalidator.JrxmlValidationDialog;
import it.businesslogic.ireport.Report;
import it.businesslogic.ireport.ReportWriter;
import it.businesslogic.ireport.gui.MainFrame;
import it.businesslogic.ireport.gui.wizard.BaseWizardPanel;
import it.businesslogic.ireport.gui.wizard.GenericWizard;
import it.businesslogic.ireport.util.Misc;
import java.awt.GridBagConstraints;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 *
 * @author  gtoffoli
 */
public class NewReportUnitWizard extends javax.swing.JPanel implements GenericWizard {
    
    private String reportFileName = null;
    private BaseWizardPanel wizardPanel = null;
    private javax.swing.JDialog wizardDialog = null;
    
    private JServer server = null;
    private String parentFolder = null;
    
    private ResourceDescriptor newResourceDescriptor = null;
    private ResourceDescriptor dataSourceDescriptor = null;
    
  
    /** Creates new form SubreportWizardPanes */
    public NewReportUnitWizard() {
        initComponents();
        
        javax.swing.event.DocumentListener dl = new javax.swing.event.DocumentListener() {
            public void changedUpdate(javax.swing.event.DocumentEvent evt) {
                if (wizardPanel != null) wizardPanel.updateButtons();
            }
            public void insertUpdate(javax.swing.event.DocumentEvent evt) {
                if (wizardPanel != null) wizardPanel.updateButtons();
            }
            public void removeUpdate(javax.swing.event.DocumentEvent evt) {
                if (wizardPanel != null) wizardPanel.updateButtons();
            }
        };
        
        this.jTextFieldLabel.getDocument().addDocumentListener( dl);
        
        this.jTextFieldName.getDocument().addDocumentListener(dl);
        
        this.jTextFieldFile.getDocument().addDocumentListener(dl);
        
        this.jEditorPaneDescription.getDocument().addDocumentListener(dl);
        
        /*
        jRTextExpressionAreaConnectionExpression.getDocument().addDocumentListener( new DocumentListener() {
            public void changedUpdate(DocumentEvent e) {
                if (wizardPanel != null) wizardPanel.updateButtons();
            }
            public void insertUpdate(DocumentEvent e) {
                if (wizardPanel != null) wizardPanel.updateButtons();
            }
            public void removeUpdate(DocumentEvent e) {
                if (wizardPanel != null) wizardPanel.updateButtons();
            }
        });
        */
        
        if (!IRPlugin.getMainInstance().getBrandingProperties().getProperty("ireport.manage.datasources.enabled", "true").equals("true"))
        {
                jPanel2.removeAll();
                GridBagConstraints  gridBagConstraints = new java.awt.GridBagConstraints();
                gridBagConstraints.gridx = 0;
                gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
                gridBagConstraints.weightx = 1.0;
                gridBagConstraints.weighty = 1.0;
                gridBagConstraints.insets = new java.awt.Insets(8, 4, 30, 4);
                QualityLabel jlabel = new QualityLabel();
                jlabel.setText("<html><b>" +  IRPlugin.getString("reportUnitDialog.useDefaultDatasource","This server uses a default data source to run the reports and execute queries") +  "</b></html>");
                jPanel2.add(jlabel, gridBagConstraints);
        }
        
        if (MainFrame.getMainInstance().getActiveReportFrame() == null)
        {
            jButtonGetCurrentReport.setEnabled(false);
        }
        
        applyI18n();
        
    }   
    
    public void startWizard()
    {
        wizardDialog = new JDialog(MainFrame.getMainInstance(),true);
        wizardPanel = new BaseWizardPanel();
        wizardPanel.setGenericWizard(this);
        wizardDialog.getContentPane().add(wizardPanel);
        wizardDialog.pack();
        jTextFieldName.requestFocusInWindow();
        Misc.centerFrame(wizardDialog);
        
        wizardDialog.setVisible(true);
    }

    private void addRequiredResources(File resourceFile, ResourceDescriptor rd) throws Exception {
        
        Report report = new Report("" + resourceFile);
        List children = RepositoryJrxmlFile.identifyElementValidationItems(report, rd);
        
        if (children.size() > 0)
        {
            // We will create a temporary file somewhere else...
            String tmpFileName = IRPlugin.createTmpFileName("newfile",".jrxml");
            System.out.println("Temp file is:" + tmpFileName);
            report.setFilename(tmpFileName);
            resourceFile = new File(tmpFileName);
            long modified = resourceFile.lastModified();
            
            JrxmlValidationDialog jvd = new JrxmlValidationDialog(MainFrame.getMainInstance(),true);
            jvd.setElementVelidationItems( children );
            jvd.setServer( getServer() );
            jvd.setReportUnit( new RepositoryReportUnit(getServer(), rd) );
            jvd.setReport( report );
            jvd.setVisible(true);
            if (jvd.getDialogResult() != JOptionPane.CANCEL_OPTION)
            {               
                // Save the report in a new temporary file and store it....
                // Look for the main jrxml...
                if (modified != resourceFile.lastModified())
                {
                    for (int i=0; i<rd.getChildren().size(); ++i)
                    {
                        ResourceDescriptor rdMainJrxml = (ResourceDescriptor)rd.getChildren().get(i);
                        if (rdMainJrxml.getWsType().equals(rdMainJrxml.TYPE_JRXML) && rdMainJrxml.isMainReport())
                        {
                            System.out.println("JRXML to modify is: " + rdMainJrxml.getUriString());
                            System.out.flush();
                            
                            rdMainJrxml.setIsNew(false);
                            rdMainJrxml.setHasData(true);
                            rdMainJrxml = getServer().getWSClient().modifyReportUnitResource(rd.getUriString(), rdMainJrxml, new File(report.getFilename()) ); 
                            // Refresh reportUnitResourceDescriptor....
                            rd.getChildren().set(i, rdMainJrxml);
                            break;
                        }
                    }
                }
            }
        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel0 = new javax.swing.JPanel();
        jLabelUriString = new javax.swing.JLabel();
        jTextFieldUriString = new javax.swing.JTextField();
        jLabelName = new javax.swing.JLabel();
        jTextFieldName = new javax.swing.JTextField();
        jSeparator2 = new javax.swing.JSeparator();
        jLabelLabel = new javax.swing.JLabel();
        jTextFieldLabel = new javax.swing.JTextField();
        jLabelDescription = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jEditorPaneDescription = new javax.swing.JEditorPane();
        jLabelError = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabelResourceFile = new javax.swing.JLabel();
        jRadioButtonRepo1 = new javax.swing.JRadioButton();
        jTextFieldFileRepo = new javax.swing.JTextField();
        jButtonPickJrxml = new javax.swing.JButton();
        jRadioButtonLocal1 = new javax.swing.JRadioButton();
        jTextFieldFile = new javax.swing.JTextField();
        jButtonBrowse = new javax.swing.JButton();
        jButtonGetCurrentReport = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabelResourceFile1 = new javax.swing.JLabel();
        jRadioButtonRepo = new javax.swing.JRadioButton();
        jComboBoxDatasources = new javax.swing.JComboBox();
        jButtonPickResource = new javax.swing.JButton();
        jRadioButtonLocal = new javax.swing.JRadioButton();
        jButtonEditLocalDataSource = new javax.swing.JButton();
        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();

        jPanel0.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jPanel0PropertyChange(evt);
            }
        });
        jPanel0.setLayout(new java.awt.GridBagLayout());

        jLabelUriString.setText("Parent folder");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        jPanel0.add(jLabelUriString, gridBagConstraints);

        jTextFieldUriString.setEditable(false);
        jTextFieldUriString.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jTextFieldUriString.setOpaque(false);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        jPanel0.add(jTextFieldUriString, gridBagConstraints);

        jLabelName.setText("Name");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4);
        jPanel0.add(jLabelName, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4);
        jPanel0.add(jTextFieldName, gridBagConstraints);

        jSeparator2.setMinimumSize(new java.awt.Dimension(0, 2));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 6, 4);
        jPanel0.add(jSeparator2, gridBagConstraints);

        jLabelLabel.setText("Label");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4);
        jPanel0.add(jLabelLabel, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        jPanel0.add(jTextFieldLabel, gridBagConstraints);

        jLabelDescription.setText("Description");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 0, 4);
        jPanel0.add(jLabelDescription, gridBagConstraints);

        jScrollPane1.setViewportView(jEditorPaneDescription);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4);
        jPanel0.add(jScrollPane1, gridBagConstraints);

        jLabelError.setForeground(new java.awt.Color(204, 0, 51));
        jLabelError.setText(" ");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        jPanel0.add(jLabelError, gridBagConstraints);

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

        jLabelResourceFile.setText("Locate the main JRXML file");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridwidth = 4;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
        gridBagConstraints.insets = new java.awt.Insets(8, 4, 20, 4);
        jPanel1.add(jLabelResourceFile, gridBagConstraints);

        buttonGroup1.add(jRadioButtonRepo1);
        jRadioButtonRepo1.setText("From the repository");
        jRadioButtonRepo1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        jRadioButtonRepo1.setMargin(new java.awt.Insets(0, 0, 0, 0));
        jRadioButtonRepo1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonRepo1jRadioButtonRepoActionPerformed1(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(8, 8, 4, 4);
        jPanel1.add(jRadioButtonRepo1, gridBagConstraints);

        jTextFieldFileRepo.setEnabled(false);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 30, 0, 0);
        jPanel1.add(jTextFieldFileRepo, gridBagConstraints);

        jButtonPickJrxml.setText("Browse");
        jButtonPickJrxml.setEnabled(false);
        jButtonPickJrxml.setMinimumSize(new java.awt.Dimension(73, 21));
        jButtonPickJrxml.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonPickJrxmljButton1ActionPerformed12(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 30);
        jPanel1.add(jButtonPickJrxml, gridBagConstraints);

        buttonGroup1.add(jRadioButtonLocal1);
        jRadioButtonLocal1.setSelected(true);
        jRadioButtonLocal1.setText("Locally Defined");
        jRadioButtonLocal1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        jRadioButtonLocal1.setMargin(new java.awt.Insets(0, 0, 0, 0));
        jRadioButtonLocal1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonLocal1jRadioButtonLocalActionPerformed1(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(8, 8, 4, 4);
        jPanel1.add(jRadioButtonLocal1, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 30, 0, 0);
        jPanel1.add(jTextFieldFile, gridBagConstraints);

        jButtonBrowse.setText("Browse");
        jButtonBrowse.setMinimumSize(new java.awt.Dimension(73, 21));
        jButtonBrowse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBrowseActionPerformed1(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 4;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 30);
        jPanel1.add(jButtonBrowse, gridBagConstraints);

        jButtonGetCurrentReport.setText("Get source from current opened report");
        jButtonGetCurrentReport.setMinimumSize(null);
        jButtonGetCurrentReport.setPreferredSize(null);
        jButtonGetCurrentReport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGetCurrentReportjButton1ActionPerformed11(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(2, 30, 2, 0);
        jPanel1.add(jButtonGetCurrentReport, gridBagConstraints);

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

        jLabelResourceFile1.setText("Locate the Data Source");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridwidth = 4;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
        gridBagConstraints.insets = new java.awt.Insets(8, 4, 20, 4);
        jPanel2.add(jLabelResourceFile1, gridBagConstraints);

        buttonGroup2.add(jRadioButtonRepo);
        jRadioButtonRepo.setText("From the repository");
        jRadioButtonRepo.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        jRadioButtonRepo.setMargin(new java.awt.Insets(0, 0, 0, 0));
        jRadioButtonRepo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonRepo1jRadioButtonRepoActionPerformed11(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(8, 8, 4, 4);
        jPanel2.add(jRadioButtonRepo, gridBagConstraints);

        jComboBoxDatasources.setEditable(true);
        jComboBoxDatasources.setEnabled(false);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 30, 4, 2);
        jPanel2.add(jComboBoxDatasources, gridBagConstraints);

        jButtonPickResource.setText("Browse");
        jButtonPickResource.setEnabled(false);
        jButtonPickResource.setMinimumSize(new java.awt.Dimension(73, 21));
        jButtonPickResource.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonPickJrxmljButton1ActionPerformed121(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 30);
        jPanel2.add(jButtonPickResource, gridBagConstraints);

        buttonGroup2.add(jRadioButtonLocal);
        jRadioButtonLocal.setSelected(true);
        jRadioButtonLocal.setText("Locally Defined");
        jRadioButtonLocal.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        jRadioButtonLocal.setMargin(new java.awt.Insets(0, 0, 0, 0));
        jRadioButtonLocal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonLocal1jRadioButtonLocalActionPerformed11(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(8, 8, 4, 4);
        jPanel2.add(jRadioButtonLocal, gridBagConstraints);

        jButtonEditLocalDataSource.setText("Edit local datasource");
        jButtonEditLocalDataSource.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEditLocalDataSourceActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 30, 0, 0);
        jPanel2.add(jButtonEditLocalDataSource, gridBagConstraints);

        setLayout(new java.awt.BorderLayout());
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonEditLocalDataSourceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEditLocalDataSourceActionPerformed
        DataSourceDialog dtd = new DataSourceDialog(MainFrame.getMainInstance(),true);
        dtd.setServer(this.getServer());
        dtd.setParentFolder( this.getParentFolder() + "/<dataSource>");
        dtd.setDoNotStore(true);
        if (dataSourceDescriptor != null) {
            dtd.setResource(dataSourceDescriptor);
        }
        
        dtd.setVisible(true);
        
        if (dtd.getDialogResult() == JOptionPane.OK_OPTION) {
            dataSourceDescriptor = dtd.getNewResourceDescriptor();
        }
    }//GEN-LAST:event_jButtonEditLocalDataSourceActionPerformed

    private void jRadioButtonLocal1jRadioButtonLocalActionPerformed11(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonLocal1jRadioButtonLocalActionPerformed11
        updateResourceFromType();
    }//GEN-LAST:event_jRadioButtonLocal1jRadioButtonLocalActionPerformed11

    private void jButtonPickJrxmljButton1ActionPerformed121(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPickJrxmljButton1ActionPerformed121
        ResourceChooser rc = new ResourceChooser();
        rc.setServer( getServer() );
        if (rc.showDialog(this, null) == JOptionPane.OK_OPTION) {
            ResourceDescriptor rd = rc.getSelectedDescriptor();
            
            if (!RepositoryExplorer.isDataSource( rd ))
            {
                JOptionPane.showMessageDialog(MainFrame.getMainInstance(),
                        IRPlugin.getString("newReportUnitWizard.selectDatasource","Please choose a DataSource resource"),
                        "",JOptionPane.WARNING_MESSAGE);
                return;
            }
            
            if (rd == null || rd.getUriString() == null) {
                jComboBoxDatasources.setSelectedItem("");
            } else {
                jComboBoxDatasources.setSelectedItem( rd.getUriString() );
            }
            if (wizardPanel != null) wizardPanel.updateButtons();
        }
    }//GEN-LAST:event_jButtonPickJrxmljButton1ActionPerformed121

    private void jRadioButtonRepo1jRadioButtonRepoActionPerformed11(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonRepo1jRadioButtonRepoActionPerformed11
        updateResourceFromType();
    }//GEN-LAST:event_jRadioButtonRepo1jRadioButtonRepoActionPerformed11

    private void jButtonGetCurrentReportjButton1ActionPerformed11(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGetCurrentReportjButton1ActionPerformed11
        
        Report report = MainFrame.getMainInstance().getActiveReportFrame().getReport();
        if (report.getFilename() == null) {
            if (JOptionPane.showConfirmDialog(this,IRPlugin.getString("newReportUnitWizard.saveReportNow","Save the report now?")) == JOptionPane.OK_OPTION) {
                MainFrame.getMainInstance().save( MainFrame.getMainInstance().getActiveReportFrame() );
            } else {
                return;
            }
        }
        jTextFieldFile.setText(  report.getFilename() );
    }//GEN-LAST:event_jButtonGetCurrentReportjButton1ActionPerformed11

    private void jButtonBrowseActionPerformed1(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBrowseActionPerformed1
        String fileName = "";
        javax.swing.JFileChooser jfc = new javax.swing.JFileChooser(MainFrame.getMainInstance().getCurrentDirectory());
        
        jfc.setDialogTitle(IRPlugin.getString("newReportUnitWizard.pickAFile","Pick a file..."));
        
        jfc.setFileFilter( new javax.swing.filechooser.FileFilter() {
            public boolean accept(java.io.File file) {
                String filename = file.getName();
                return (filename.toLowerCase().endsWith(".xml") || file.isDirectory() || filename.toLowerCase().endsWith(".jrxml")) ;
            }
            public String getDescription() {
                return "JasperReports XML *.xml, *.jrxml";
            }
        });
        
        jfc.setMultiSelectionEnabled(false);
        jfc.setDialogType( javax.swing.JFileChooser.OPEN_DIALOG);
        if  (jfc.showOpenDialog( this) == javax.swing.JOptionPane.OK_OPTION) {
            
            jTextFieldFile.setText(  jfc.getSelectedFile()+"");
            if (wizardPanel != null) wizardPanel.updateButtons();
        }
    }//GEN-LAST:event_jButtonBrowseActionPerformed1

    private void jRadioButtonLocal1jRadioButtonLocalActionPerformed1(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonLocal1jRadioButtonLocalActionPerformed1
       updateJrxmlFromType();
    }//GEN-LAST:event_jRadioButtonLocal1jRadioButtonLocalActionPerformed1

    private void jButtonPickJrxmljButton1ActionPerformed12(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPickJrxmljButton1ActionPerformed12
        ResourceChooser rc = new ResourceChooser();
        rc.setServer( getServer() );
        if (rc.showDialog(this, null) == JOptionPane.OK_OPTION) {
            ResourceDescriptor rd = rc.getSelectedDescriptor();
            
            if (rd == null || rd.getUriString() == null) {
                jTextFieldFileRepo.setText("");
            } else {
                if (!rd.getWsType().equals(rd.TYPE_JRXML) ) {
                    JOptionPane.showMessageDialog(MainFrame.getMainInstance(),
                            IRPlugin.getString("newReportUnitWizard.chooseJRXML","Please choose a JRXML resource"),"",JOptionPane.WARNING_MESSAGE);
                    return;
                } else {
                    jTextFieldFileRepo.setText( rd.getUriString() );
                }
            }
        }
    }//GEN-LAST:event_jButtonPickJrxmljButton1ActionPerformed12

    private void jRadioButtonRepo1jRadioButtonRepoActionPerformed1(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonRepo1jRadioButtonRepoActionPerformed1
        updateJrxmlFromType();
    }//GEN-LAST:event_jRadioButtonRepo1jRadioButtonRepoActionPerformed1

    private void jPanel0PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jPanel0PropertyChange

        
        
    }//GEN-LAST:event_jPanel0PropertyChange
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JButton jButtonBrowse;
    private javax.swing.JButton jButtonEditLocalDataSource;
    private javax.swing.JButton jButtonGetCurrentReport;
    private javax.swing.JButton jButtonPickJrxml;
    private javax.swing.JButton jButtonPickResource;
    private javax.swing.JComboBox jComboBoxDatasources;
    private javax.swing.JEditorPane jEditorPaneDescription;
    private javax.swing.JLabel jLabelDescription;
    private javax.swing.JLabel jLabelError;
    private javax.swing.JLabel jLabelLabel;
    private javax.swing.JLabel jLabelName;
    private javax.swing.JLabel jLabelResourceFile;
    private javax.swing.JLabel jLabelResourceFile1;
    private javax.swing.JLabel jLabelUriString;
    private javax.swing.JPanel jPanel0;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JRadioButton jRadioButtonLocal;
    private javax.swing.JRadioButton jRadioButtonLocal1;
    private javax.swing.JRadioButton jRadioButtonRepo;
    private javax.swing.JRadioButton jRadioButtonRepo1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JTextField jTextFieldFile;
    private javax.swing.JTextField jTextFieldFileRepo;
    private javax.swing.JTextField jTextFieldLabel;
    private javax.swing.JTextField jTextFieldName;
    private javax.swing.JTextField jTextFieldUriString;
    // End of variables declaration//GEN-END:variables


    public String[] getStepsNames() {
        
        String[] names = new String[3];
        names[0] = IRPlugin.getString("newReportUnitWizard.step.naming","Naming");
        names[1] = IRPlugin.getString("newReportUnitWizard.step.jrxml","Main JRXML");
        names[2] = IRPlugin.getString("newReportUnitWizard.step.datasource","Locate Data Source");
        //names[3] = "Resources List";
        //names[4] = "Finish";
        
        return names;
    }

    public String getStepDescription(int step) {
        
        if (step==0) return IRPlugin.getString("newReportUnitWizard.stepdesc.naming","Report name and label");
        if (step==1) return IRPlugin.getString("newReportUnitWizard.stepdesc.jrxml","The main JRXML source file");
        if (step==2) return IRPlugin.getString("newReportUnitWizard.stepdesc.datasource","Locate the datasource to use with this report");
        if (step==3) return IRPlugin.getString("newReportUnitWizard.stepdesc.addinputcontrols","Add input controls and other resources");
        if (step==4) return IRPlugin.getString("newReportUnitWizard.stepdesc.save","Save");
        
        return "";
    }

    public void initWizard() {
        
    }

    public void finish(int currentStep) {
        
        
        if (currentStep > 0)
        {
            File resourceFile = null;
            ResourceDescriptor rd = new ResourceDescriptor();
        
            try {
                    rd.setWsType( ResourceDescriptor.TYPE_REPORTUNIT );
                    rd.setDescription( jEditorPaneDescription.getText().trim() ); //getResource().getDescriptor().getDescription()
                    rd.setName( jTextFieldName.getText()  );
                    String uri = getParentFolder();
                    if (!uri.endsWith("/")) uri = uri + "/";
                    uri += jTextFieldName.getText();
                    rd.setUriString( uri );
                    rd.setLabel(jTextFieldLabel.getText().trim() ); //getResource().getDescriptor().getLabel()  );
                    rd.setParentFolder( getParentFolder() );
                    rd.setIsNew( true );

                    // Add the datasource resource...
                    if (IRPlugin.getMainInstance().getBrandingProperties().getProperty("ireport.manage.datasources.enabled", "true").equals("true"))
                    {
                        ResourceDescriptor tmpDataSourceDescriptor;
                        if (jRadioButtonRepo.isSelected())
                        {
                            tmpDataSourceDescriptor = new ResourceDescriptor();
                            tmpDataSourceDescriptor.setWsType( ResourceDescriptor.TYPE_DATASOURCE );
                            tmpDataSourceDescriptor.setReferenceUri( jComboBoxDatasources.getSelectedItem()+"");
                            tmpDataSourceDescriptor.setIsReference(true);
                        }
                        else
                        {
                            if (dataSourceDescriptor == null)
                            {
                                JOptionPane.showMessageDialog(this,
                                        IRPlugin.getString("newReportUnitWizard.message.datasourceNotDefined","The local datasource is not correctly defined.\nPress the button \"Edit local datasource\" to fix the problem.")
                                        );
                                return;
                            }
                            tmpDataSourceDescriptor = dataSourceDescriptor;
                            tmpDataSourceDescriptor.setIsReference(false);
                        }

                        rd.getChildren().add( tmpDataSourceDescriptor );

                    }


                    // Add the jrxml resource...
                    ResourceDescriptor jrxmlDescriptor = new ResourceDescriptor();
                    jrxmlDescriptor.setWsType( ResourceDescriptor.TYPE_JRXML );

                    if (jRadioButtonRepo1.isSelected())
                    {
                        jrxmlDescriptor.setIsNew(true);
                        jrxmlDescriptor.setMainReport(true);
                        jrxmlDescriptor.setIsReference(true);
                        jrxmlDescriptor.setReferenceUri( jTextFieldFileRepo.getText() );
                    }
                    else
                    {
                            jrxmlDescriptor.setName( jTextFieldName.getText() + "_jrxml");
                            jrxmlDescriptor.setLabel("Main jrxml"); //getResource().getDescriptor().getLabel()  );
                            jrxmlDescriptor.setDescription("Main jrxml"); //getResource().getDescriptor().getDescription()
                            jrxmlDescriptor.setIsNew(true);
                            jrxmlDescriptor.setHasData(true);
                            jrxmlDescriptor.setMainReport(true);
                            resourceFile = new File( jTextFieldFile.getText());

                            if (!resourceFile.exists()) {
                                JOptionPane.showMessageDialog(this, 
                                        IRPlugin.getFormattedString("newReportUnitWizard.message.fileNotFound","{0}\n\nFile not found!",new Object[]{jTextFieldFile.getText()}));
                                return;
                            }  
                    }
                    rd.getChildren().add( jrxmlDescriptor );
                        
                newResourceDescriptor = getServer().getWSClient().addOrModifyResource(rd, resourceFile);
                if (resourceFile != null)
                {
                    addRequiredResources(resourceFile, newResourceDescriptor);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this,IRPlugin.getFormattedString("messages.error.3", "Error:\n {0}", new Object[] {ex.getMessage()}));
                ex.printStackTrace();
                return;
            }
        }
        
        this.getWizardDialog().setVisible(false);
        this.getWizardDialog().dispose();
    }
    
    public boolean nextStep(int nextStep) {
        
        if (nextStep == 0) // First step == 0
        {
        } 
        else if (nextStep == 1) // First step == 0
        {
           
        }
        else if (nextStep == 2) // First step == 0
        {
           
        }
        return true;
    }

    public boolean previousStep(int previousStep) {
        return true;
    }

    public boolean canFinish(int currentStep) {
         if (currentStep < 2) return false;
         if (currentStep == 2 )
         {
             if (jRadioButtonRepo.isSelected() && jComboBoxDatasources.getSelectedItem() != null
                && jComboBoxDatasources.getSelectedItem().toString().trim().length() > 0) return true;
             if (jRadioButtonLocal.isSelected() && dataSourceDescriptor != null) return true;
         }
         return true;
    }

    public boolean canNext(int currentStep) {
        if (currentStep == 0)
        {
            jLabelError.setText("");
            try {
                
                ValidationUtils.validateName( jTextFieldName.getText() );
                ValidationUtils.validateLabel( jTextFieldLabel.getText() );
                ValidationUtils.validateDesc( jEditorPaneDescription.getText() );
                
            } catch (Exception ex)
            {
                jLabelError.setText(ex.getMessage());
                return false;
            }
            return true;
        }
        else if (currentStep == 1)
        {
            if (jRadioButtonRepo1.isSelected() && jTextFieldFileRepo.getText().trim().length() > 0) return true;
            if (jRadioButtonLocal1.isSelected() && jTextFieldFile.getText().trim().length() > 0) return true;
        }
        else if (currentStep == 2)
        {
            return false;
            
        }
        return false;
    }

    public boolean canPrevious(int currentStep) {
        return (currentStep > 0);
    }

    public JPanel getStepPanel(int step) {
       if (step == 0) return jPanel0;
       if (step == 1) return jPanel1;
       if (step == 2) return jPanel2;
       //if (step == 3) return jPanel3;
       return  null;
    }

    public BaseWizardPanel getWizardPanel() {
        return wizardPanel;
    }

    public void setWizardPanel(BaseWizardPanel wizardPanel) {
        this.wizardPanel = wizardPanel;
    }

    public javax.swing.JDialog getWizardDialog() {
        return wizardDialog;
    }

    public void setWizardDialog(javax.swing.JDialog wizardDialog) {
        this.wizardDialog = wizardDialog;
    }

    public JServer getServer() {
        return server;
    }

    public void setServer(JServer server) {
        this.server = server;
    }

    public String getParentFolder() {
        return parentFolder;
    }

    public void setParentFolder(String parentFolder) {
        this.parentFolder = parentFolder;
        jTextFieldUriString.setText(parentFolder);
    }
    
    
    public void updateJrxmlFromType()
    {
        jTextFieldFileRepo.setEnabled( jRadioButtonRepo1.isSelected() );
        jButtonPickJrxml.setEnabled( jRadioButtonRepo1.isSelected() );
        jTextFieldFile.setEnabled( jRadioButtonLocal1.isSelected() );
        jButtonBrowse.setEnabled( jRadioButtonLocal1.isSelected() );
        jButtonGetCurrentReport.setEnabled( jRadioButtonLocal1.isSelected() );
        
        if (wizardPanel != null) wizardPanel.updateButtons();
    }
    
    public void updateResourceFromType()
    {
        jComboBoxDatasources.setEnabled( jRadioButtonRepo.isSelected() );
        jButtonPickResource.setEnabled( jRadioButtonRepo.isSelected() );
        jButtonEditLocalDataSource.setEnabled( jRadioButtonLocal.isSelected() );
        
        if (wizardPanel != null) wizardPanel.updateButtons();
    }
    
    /**
     * Accept a list of Strings or ResourceDescriptor
     */
    public void setDatasources(List datasources)
    {
        jComboBoxDatasources.removeAllItems();
        for (int i=0; i<datasources.size(); ++i)
        {
            Object datasource = datasources.get(i);
            if (datasource instanceof java.lang.String)
            {
                jComboBoxDatasources.addItem(datasource);
            }
            else if (datasource instanceof ResourceDescriptor)
            {
                jComboBoxDatasources.addItem(((ResourceDescriptor)datasource).getUriString());
            }
        }
        
        if (jComboBoxDatasources.getItemCount() > 0)
        {
            jComboBoxDatasources.setSelectedIndex(0);
        }
    }

    public ResourceDescriptor getNewResourceDescriptor() {
        return newResourceDescriptor;
    }
    
    public void applyI18n()
    {
        jLabelDescription.setText( IRPlugin.getString("newReportUnitWizard.labelDescription","Description"));
        jLabelLabel.setText( IRPlugin.getString("newReportUnitWizard.labelLabel","Label"));
        jLabelName.setText( IRPlugin.getString("newReportUnitWizard.labelName","Name"));
        jLabelUriString.setText( IRPlugin.getString("newReportUnitWizard.labelParentFolder","Parent folder"));
        
        /*
        jLabelPassword.setText( IRPlugin.getString("xmlaConnectionDialog.labelPassword","Password"));
        jLabelURL.setText( IRPlugin.getString("xmlaConnectionDialog.labelURI","URI"));
        jLabelCatalog.setText( IRPlugin.getString("xmlaConnectionDialog.labelCatalog","Catalog"));
        jLabelDatasource.setText( IRPlugin.getString("xmlaConnectionDialog.labelDatasource","Data Source"));
        jLabelUsername.setText( IRPlugin.getString("xmlaConnectionDialog.labelUsername","Username"));
        jTabbedPane1.setTitleAt(0, IRPlugin.getString("xmlaConnectionDialog.tabGeneral","General") );
        jTabbedPane1.setTitleAt(1, IRPlugin.getString("xmlaConnectionDialog.tabDetails","XMLA/A connection details") );
         */
    }
}
