/*  VirtualDatasourceItemDialog.java
 *
 * Created on Nov 2, 2012, 10:19:18 PM
 */

package com.jaspersoft.ireport.jasperserver.ui.resources;

import com.jaspersoft.ireport.jasperserver.JServer;
import com.jaspersoft.ireport.jasperserver.JasperServerManager;
import com.jaspersoft.ireport.jasperserver.ui.ResourceChooser;
import com.jaspersoft.ireport.locale.I18n;
import com.jaspersoft.jasperserver.api.metadata.xml.domain.impl.ResourceDescriptor;
import java.util.Map;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.util.JRStringUtil;
import net.sf.jasperreports.engine.util.JRXmlUtils;


/**
 *
 * @author gtoffoli
 */


public class VirtualDatasourceItemDialog extends javax.swing.JDialog {

    private ResourceDescriptor resourceDescriptor = null;
    private JServer server = null;
    private Pattern subDsIdInvalidChars = Pattern.compile("\\W");
    private String oldName = "";
    
    
    private Map<String, ResourceDescriptor> existingResourceDescriptors = null;
    
    
    private int dialogResult = JOptionPane.CANCEL_OPTION;
    
    
    /** Creates new form VirtualDatasourceItemDialog */
    public VirtualDatasourceItemDialog(java.awt.Dialog parent, boolean modal) {
        super(parent, modal);
        initComponents();
        
        
        this.setLocationRelativeTo(null);
        
        javax.swing.KeyStroke escape =  javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, 0, false);
        javax.swing.Action escapeAction = new javax.swing.AbstractAction() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                jButtonCloseActionPerformed(e);
            }
        };
        getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escape, I18n.getString("Global.Pane.Escape"));
        getRootPane().getActionMap().put(I18n.getString("Global.Pane.Escape"), escapeAction);

        //to make the default button ...
        getRootPane().setDefaultButton(jButtonClose);

        
    }
    
    
    
    public void setResourceDescriptor(ResourceDescriptor rd)
    {
        resourceDescriptor = rd;
        
        oldName = rd.getResourcePropertyValue("PROP_DATASOURCE_SUB_DS_ID");
        jTextFieldName.setText( rd.getResourcePropertyValue("PROP_DATASOURCE_SUB_DS_ID") );
        jTextFieldUri.setText( rd.getResourcePropertyValue("PROP_REFERENCE_URI") );
    
    }
    
    public ResourceDescriptor getResourceDescriptor()
    {
        return resourceDescriptor;
    }

    
    /** 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jLabelName = new javax.swing.JLabel();
        jTextFieldName = new javax.swing.JTextField();
        jLabelUri = new javax.swing.JLabel();
        jTextFieldUri = new javax.swing.JTextField();
        jButtonBrowse = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jPanel4 = new javax.swing.JPanel();
        jButtonSave = new javax.swing.JButton();
        jButtonClose = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(500, 200));
        getContentPane().setLayout(new java.awt.GridBagLayout());

        jLabelName.setText(org.openide.util.NbBundle.getMessage(VirtualDatasourceItemDialog.class, "VirtualDatasourceItemDialog.jLabelName.text")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(8, 4, 0, 0);
        getContentPane().add(jLabelName, gridBagConstraints);

        jTextFieldName.setText(org.openide.util.NbBundle.getMessage(VirtualDatasourceItemDialog.class, "VirtualDatasourceItemDialog.jTextFieldName.text")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4);
        getContentPane().add(jTextFieldName, gridBagConstraints);

        jLabelUri.setText(org.openide.util.NbBundle.getMessage(VirtualDatasourceItemDialog.class, "VirtualDatasourceItemDialog.jLabelUri.text")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 0, 0);
        getContentPane().add(jLabelUri, gridBagConstraints);

        jTextFieldUri.setText(org.openide.util.NbBundle.getMessage(VirtualDatasourceItemDialog.class, "VirtualDatasourceItemDialog.jTextFieldUri.text")); // NOI18N
        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, 4, 0, 0);
        getContentPane().add(jTextFieldUri, gridBagConstraints);

        jButtonBrowse.setText(org.openide.util.NbBundle.getMessage(VirtualDatasourceItemDialog.class, "VirtualDatasourceItemDialog.jButtonBrowse.text")); // NOI18N
        jButtonBrowse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBrowseActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 0, 0);
        getContentPane().add(jButtonBrowse, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH;
        gridBagConstraints.weighty = 1.0;
        getContentPane().add(jSeparator1, gridBagConstraints);

        jPanel4.setMinimumSize(new java.awt.Dimension(10, 30));
        jPanel4.setPreferredSize(new java.awt.Dimension(500, 30));
        jPanel4.setLayout(new java.awt.GridBagLayout());

        jButtonSave.setText(org.openide.util.NbBundle.getMessage(VirtualDatasourceItemDialog.class, "VirtualDatasourceItemDialog.jButtonSave.text")); // NOI18N
        jButtonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSaveActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4);
        jPanel4.add(jButtonSave, gridBagConstraints);

        jButtonClose.setText(org.openide.util.NbBundle.getMessage(VirtualDatasourceItemDialog.class, "VirtualDatasourceItemDialog.jButtonClose.text")); // NOI18N
        jButtonClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCloseActionPerformed(evt);
            }
        });
        jPanel4.add(jButtonClose, new java.awt.GridBagConstraints());

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        getContentPane().add(jPanel4, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

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

         try {      
             
                 if (jTextFieldName.getText().length() == 0)
                 {
                     jTextFieldName.requestFocus();
                     throw new IllegalArgumentException("Please specify a valid ID for this datasource item");
                 }
                 

                    if(subDsIdInvalidChars.matcher(jTextFieldName.getText()).find()) {
                        jTextFieldName.requestFocus();
                        throw new IllegalArgumentException("Only letters, digits and underscore allowed in ID");
                    }

                 
                 if (!jTextFieldName.getText().equals(oldName) &&
                      existingResourceDescriptors.containsKey(jTextFieldName.getText()))
                 {
                     jTextFieldName.requestFocus();
                     throw new IllegalArgumentException("This name is already used by another datasource item,\nplease specify a different one.");
                 }
                 
                 
                 if (jTextFieldUri.getText().length() == 0)
                 {
                     
                     jTextFieldUri.requestFocus();
                     throw new IllegalArgumentException("Please specify a valid URI");
                 }
                 
         	 //getResource().getDescriptor().getDescription()             
         	 
                 
                 if (resourceDescriptor == null)
                 {
                    resourceDescriptor = new ResourceDescriptor();
                    resourceDescriptor.setName("");
                    resourceDescriptor.setLabel("");
                    resourceDescriptor.setWsType("datasource");
                    resourceDescriptor.setUriString("");
                 }
                 
                 resourceDescriptor.setResourceProperty("PROP_DATASOURCE_SUB_DS_ID", jTextFieldName.getText());
                 resourceDescriptor.setResourceProperty("PROP_REFERENCE_URI", jTextFieldUri.getText());
                 
                 
                this.setDialogResult(JOptionPane.OK_OPTION);
                this.setVisible(false);
                this.dispose();
          } catch (Exception ex) {             
              JOptionPane.showMessageDialog(this, JasperServerManager.getFormattedString("messages.error.3", "Error:\n {0}", new Object[]{ex.getMessage()}));
             ex.printStackTrace();
             return;
         }    
    
    }//GEN-LAST:event_jButtonSaveActionPerformed

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

         this.setVisible(false);         this.dispose();     }//GEN-LAST:event_jButtonCloseActionPerformed

    private void jButtonBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBrowseActionPerformed
        
        
        ResourceChooser rc = new ResourceChooser();
        rc.setServer( getServer() );
        
        if (rc.showDialog(this, null) == JOptionPane.OK_OPTION)
        {
            ResourceDescriptor rd = rc.getSelectedDescriptor();
            
            
            if (!(rd.getWsType().equals(ResourceDescriptor.TYPE_DATASOURCE_JDBC) ||
                  rd.getWsType().equals(ResourceDescriptor.TYPE_DATASOURCE_JNDI) ))
             {
                 JOptionPane.showMessageDialog(this, "Please select a datasource of type JDBC or JNDI");   
                 return;
             }
            
            if (rd == null || rd.getUriString() == null) 
            {
                jTextFieldUri.setText("");
            }
            else
            {
                jTextFieldUri.setText( rd.getUriString() );
                
                // Suggest a valid name...
                
                String baseName = rd.getLabel();
                
                baseName = baseName.replace(" ", "_");
                baseName = JRStringUtil.getJavaIdentifier(baseName);
                
                String newName = baseName;
                
                int k=0;
                
                while (!oldName.equals(newName) &&  existingResourceDescriptors.containsKey(newName ) )
                {
                    k++;
                    newName = baseName + "_" + k;
                }
                
                jTextFieldName.setText(newName );
            }
        }
        
        
    }//GEN-LAST:event_jButtonBrowseActionPerformed

    
        
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonBrowse;
    private javax.swing.JButton jButtonClose;
    private javax.swing.JButton jButtonSave;
    private javax.swing.JLabel jLabelName;
    private javax.swing.JLabel jLabelUri;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField jTextFieldName;
    private javax.swing.JTextField jTextFieldUri;
    // End of variables declaration//GEN-END:variables

    /**
     * @return the dialogResult
     */
    public int getDialogResult() {
        return dialogResult;
    }

    /**
     * @param dialogResult the dialogResult to set
     */
    public void setDialogResult(int dialogResult) {
        this.dialogResult = dialogResult;
    }

    /**
     * @return the existingResourceDescriptors
     */
    public Map<String, ResourceDescriptor> getExistingResourceDescriptors() {
        return existingResourceDescriptors;
    }

    /**
     * @param existingResourceDescriptors the existingResourceDescriptors to set
     */
    public void setExistingResourceDescriptors(Map<String, ResourceDescriptor> existingResourceDescriptors) {
        this.existingResourceDescriptors = existingResourceDescriptors;
    }

    /**
     * @return the server
     */
    public JServer getServer() {
        return server;
    }

    /**
     * @param server the server to set
     */
    public void setServer(JServer server) {
        this.server = server;
    }
}
