/*
 * iReport - Visual Designer for JasperReports.
 * Copyright (C) 2002 - 2009 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 part of iReport.
 *
 * iReport 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.
 *
 * iReport 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 iReport. If not, see <http://www.gnu.org/licenses/>.
 */
package com.jaspersoft.ireport.jasperserver.ui.wizards;

import com.jaspersoft.ireport.designer.utils.Misc;
import com.jaspersoft.ireport.jasperserver.JServer;
import com.jaspersoft.ireport.jasperserver.JasperServerManager;
import com.jaspersoft.ireport.jasperserver.RepositoryFolder;
import com.jaspersoft.ireport.jasperserver.ui.QualityLabel;
import com.jaspersoft.ireport.jasperserver.ui.ResourceChooser;
import com.jaspersoft.ireport.jasperserver.ui.resources.DataSourceDialog;
import com.jaspersoft.jasperserver.api.metadata.xml.domain.impl.ResourceDescriptor;
import java.awt.GridBagConstraints;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public final class ReportUnitVisualPanel3 extends JPanel {

    ReportUnitWizardPanel3 wizardPanel = null;
    private ResourceDescriptor dataSourceDescriptor = null;
    
    /** Creates new form ReportUnitVisualPanel3 */
    public ReportUnitVisualPanel3(ReportUnitWizardPanel3 wizardPanel) {
        initComponents();
        this.wizardPanel = wizardPanel;
        
        if (!JasperServerManager.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>" +  JasperServerManager.getString("reportUnitDialog.useDefaultDatasource","This server uses a default data source to run the reports and execute queries") +  "</b></html>");
                jPanel2.add(jlabel, gridBagConstraints);
        }
        
        
        jComboBoxDatasources.removeAllItems();
        List datasources = wizardPanel.getWizardDescriptor().getDatasources();
        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 JServer getServer()
    {
        return wizardPanel.getWizardDescriptor().getServer();
    }
    
    public String getParentFolder()
    {
        return wizardPanel.getWizardDescriptor().getParentFolder();
    }

    @Override
    public String getName() {
        return JasperServerManager.getString("newReportUnitWizard.step.datasource","Locate Data Source");
    }

    /** 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;

        buttonGroup1 = new javax.swing.ButtonGroup();
        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();

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

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

        org.openide.awt.Mnemonics.setLocalizedText(jLabelResourceFile1, "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);

        buttonGroup1.add(jRadioButtonRepo);
        org.openide.awt.Mnemonics.setLocalizedText(jRadioButtonRepo, "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);

        org.openide.awt.Mnemonics.setLocalizedText(jButtonPickResource, "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) {
                jButtonPickResourcejButtonPickJrxmljButton1ActionPerformed121(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 30);
        jPanel2.add(jButtonPickResource, gridBagConstraints);

        buttonGroup1.add(jRadioButtonLocal);
        jRadioButtonLocal.setSelected(true);
        org.openide.awt.Mnemonics.setLocalizedText(jRadioButtonLocal, "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);

        org.openide.awt.Mnemonics.setLocalizedText(jButtonEditLocalDataSource, "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);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        add(jPanel2, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents

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

    private void jButtonPickResourcejButtonPickJrxmljButton1ActionPerformed121(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPickResourcejButtonPickJrxmljButton1ActionPerformed121
        ResourceChooser rc = new ResourceChooser();
        rc.setServer( getServer() );
        if (rc.showDialog(this, null) == JOptionPane.OK_OPTION) {
            ResourceDescriptor rd = rc.getSelectedDescriptor();
            
            if (!RepositoryFolder.isDataSource( rd )) {
                JOptionPane.showMessageDialog(Misc.getMainFrame(),
                        JasperServerManager.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.fireChangeEvent();
        }
    }//GEN-LAST:event_jButtonPickResourcejButtonPickJrxmljButton1ActionPerformed121

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

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

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButtonEditLocalDataSource;
    private javax.swing.JButton jButtonPickResource;
    private javax.swing.JComboBox jComboBoxDatasources;
    private javax.swing.JLabel jLabelResourceFile1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JRadioButton jRadioButtonLocal;
    private javax.swing.JRadioButton jRadioButtonRepo;
    // End of variables declaration//GEN-END:variables

    void storeSettings(ReportUnitWizardDescriptor wizardDescriptor) {
        
        if (!JasperServerManager.getMainInstance().getBrandingProperties().getProperty("ireport.manage.datasources.enabled", "true").equals("true"))
        {
            // No datasource required...
            return;
        }
        
        wizardDescriptor.putProperty("datasource_is_local", jRadioButtonLocal.isSelected()+"");
        if (jRadioButtonLocal.isSelected())
        {
            wizardDescriptor.putProperty("datasource_descriptor", dataSourceDescriptor );
        }
        else
        {
            wizardDescriptor.putProperty("datasource_uri", jComboBoxDatasources.getSelectedItem());
        }
    }
        
    public void validateForm() throws Exception
    {
        if (!JasperServerManager.getMainInstance().getBrandingProperties().getProperty("ireport.manage.datasources.enabled", "true").equals("true"))
        {
            // No datasource required...
            return;
        }
        
        if (jRadioButtonRepo.isSelected() && (jComboBoxDatasources.getSelectedItem() == null
                || jComboBoxDatasources.getSelectedItem().toString().trim().length() == 0))
        {
            throw new Exception("No datasource selected.");
        }
        if (jRadioButtonLocal.isSelected() && dataSourceDescriptor == null)
        {
            throw new Exception(JasperServerManager.getString("newReportUnitWizard.message.datasourceNotDefined","The local datasource is not correctly defined.\nPress the button \"Edit local datasource\" to fix the problem."));
        }
    }
    
     public void updateResourceFromType()
    {
        jComboBoxDatasources.setEnabled( jRadioButtonRepo.isSelected() );
        jButtonPickResource.setEnabled( jRadioButtonRepo.isSelected() );
        jButtonEditLocalDataSource.setEnabled( jRadioButtonLocal.isSelected() );
        
        if (wizardPanel != null) wizardPanel.fireChangeEvent();
    }

    public ResourceDescriptor getDataSourceDescriptor() {
        return dataSourceDescriptor;
    }

    public void setDataSourceDescriptor(ResourceDescriptor dataSourceDescriptor) {
        this.dataSourceDescriptor = dataSourceDescriptor;
    }
}

