/*
 * LibraryPanel.java
 *
 * Created on 14 settembre 2004, 23.49
 */

package it.businesslogic.ireport.gui.library;
import it.businesslogic.ireport.gui.library.objects.*;
import it.businesslogic.ireport.gui.*;
import it.businesslogic.ireport.*;
import it.businesslogic.ireport.gui.docking.GenericDragTargetListener;
import it.businesslogic.ireport.gui.subdataset.SubDatasetDialog;
import it.businesslogic.ireport.util.Misc;
import java.awt.dnd.DropTarget;
import javax.swing.*;
import javax.swing.tree.*;
import java.util.*;
import java.awt.event.ActionEvent;

/**
 *
 * @author  Administrator
 */
public class LibraryPanel extends javax.swing.JPanel
       implements
            it.businesslogic.ireport.util.LanguageChangedListener,
            it.businesslogic.ireport.gui.event.SubDatasetObjectChangedListener,
            it.businesslogic.ireport.gui.event.ReportSubDatasetChangedListener {

    DefaultMutableTreeNode fieldsNode = null;
    DefaultMutableTreeNode variablesNode = null;
    DefaultMutableTreeNode parametersNode = null;
    DefaultMutableTreeNode systemObjectsNode = null;

    JReportFrame jrf;


    /** Creates new form LibraryPanel */
    public LibraryPanel() {

        initComponents();

        jLibraryTree.setCellRenderer( new LibraryTreeCellRenderer());
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Libs");

        DefaultTreeModel dtm = new DefaultTreeModel(root);

        jLibraryTree.setModel( dtm );
        jLibraryTree.setDragEnabled(true);
        jLibraryTree.setRootVisible( false );
        jLibraryTree.setTransferHandler(new TreeTransfertHandler());

        jLibraryTree.setDropTarget(new DropTarget(this, new GenericDragTargetListener()));

        jLibraryTree.expandPath( new TreePath(root));

        fieldsNode = new DefaultMutableTreeNode("Fields",true);
        root.add( fieldsNode );

        variablesNode = new DefaultMutableTreeNode("Variables",true);
        root.add( variablesNode );

        parametersNode = new DefaultMutableTreeNode("Parameters",true);
        root.add( parametersNode );

        this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
       	 KeyStroke.getKeyStroke("F5"), "refresh");
         this.getActionMap().put("refresh",
            new AbstractAction("refresh") {
              public void actionPerformed(ActionEvent evt) {
                setJReportFrame(jrf);
              }
        });
/*
        systemObjectsNode = new DefaultMutableTreeNode("Custom",true);
        root.add( systemObjectsNode );
*/
        it.businesslogic.ireport.util.I18n.addOnLanguageChangedListener( this );

        loadSystemObjects();
        loadCustomObjects();

        updateReportObjects();
        this.languageChanged(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() {
        jPopupMenuFields = new javax.swing.JPopupMenu();
        jMenuItemEdit = new javax.swing.JMenuItem();
        jMenuAdd = new javax.swing.JMenu();
        jMenuItemNewField = new javax.swing.JMenuItem();
        jMenuItemNewVariable = new javax.swing.JMenuItem();
        jMenuItemParameter = new javax.swing.JMenuItem();
        jSeparator3 = new javax.swing.JSeparator();
        jMenuItemNewSubDataset = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        jMenuItemCut = new javax.swing.JMenuItem();
        jMenuItemCopy = new javax.swing.JMenuItem();
        jMenuItemPaste = new javax.swing.JMenuItem();
        jMenuItemDelete = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JSeparator();
        jMenuItemRefresh = new javax.swing.JMenuItem();
        jScrollPane1 = new javax.swing.JScrollPane();
        jLibraryTree = new javax.swing.JTree();

        jPopupMenuFields.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
                jPopupMenuFieldsPopupMenuWillBecomeVisible(evt);
            }
        });

        jMenuItemEdit.setIcon(new javax.swing.ImageIcon(""));
        //Modified by Felix Firgau for I18n on Feb 9th 2006
        jMenuItemEdit.setText(it.businesslogic.ireport.util.I18n.getString("edit", "Edit"));
        jMenuItemEdit.setEnabled(false);
        jMenuItemEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemEditActionPerformed(evt);
            }
        });

        jPopupMenuFields.add(jMenuItemEdit);

        //Modified by Felix Firgau for I18n on Feb 9th 2006
        jMenuAdd.setText(it.businesslogic.ireport.util.I18n.getString("add", "Add"));//End
        jMenuItemNewField.setIcon(new javax.swing.ImageIcon(""));
        jMenuItemNewField.setText("Field");
        jMenuItemNewField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemNewFieldActionPerformed(evt);
            }
        });

        jMenuAdd.add(jMenuItemNewField);

        jMenuItemNewVariable.setIcon(new javax.swing.ImageIcon(""));
        jMenuItemNewVariable.setText("Variable");
        jMenuItemNewVariable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemNewVariableActionPerformed(evt);
            }
        });

        jMenuAdd.add(jMenuItemNewVariable);

        jMenuItemParameter.setIcon(new javax.swing.ImageIcon(""));
        jMenuItemParameter.setText("Parameter");
        jMenuItemParameter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemParameterActionPerformed(evt);
            }
        });

        jMenuAdd.add(jMenuItemParameter);

        jMenuAdd.add(jSeparator3);

        jMenuItemNewSubDataset.setText("Sub dataset");
        jMenuItemNewSubDataset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemNewSubDatasetActionPerformed(evt);
            }
        });

        jMenuAdd.add(jMenuItemNewSubDataset);

        jPopupMenuFields.add(jMenuAdd);

        jPopupMenuFields.add(jSeparator1);

        jMenuItemCut.setIcon(new javax.swing.ImageIcon(getClass().getResource("/it/businesslogic/ireport/icons/menu/cut.png")));
        //Modiefied by Felix Firgau for I18n on Feb 9th 2006
        jMenuItemCut.setText(it.businesslogic.ireport.util.I18n.getString("cut", "Cut"));
        jMenuItemCut.setEnabled(false);
        jMenuItemCut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemCutActionPerformed(evt);
            }
        });

        jPopupMenuFields.add(jMenuItemCut);

        jMenuItemCopy.setIcon(new javax.swing.ImageIcon(getClass().getResource("/it/businesslogic/ireport/icons/menu/copy.png")));
        //Modified by Felix Firgau on Feb 9th 2006
        jMenuItemCopy.setText(it.businesslogic.ireport.util.I18n.getString("copy", "Copy"));
        jMenuItemCopy.setEnabled(false);
        jMenuItemCopy.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemCopyActionPerformed(evt);
            }
        });

        jPopupMenuFields.add(jMenuItemCopy);

        jMenuItemPaste.setIcon(new javax.swing.ImageIcon(getClass().getResource("/it/businesslogic/ireport/icons/menu/paste.png")));
        //Modified by Felix Firgau on Feb 9th 2006
        jMenuItemPaste.setText(it.businesslogic.ireport.util.I18n.getString("paste", "Paste"));
        jMenuItemPaste.setEnabled(false);
        jMenuItemPaste.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemPasteActionPerformed(evt);
            }
        });

        jPopupMenuFields.add(jMenuItemPaste);

        jMenuItemDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/it/businesslogic/ireport/icons/menu/delete.png")));
        //Modified by Felix Firgau on Feb 9th 2006
        jMenuItemDelete.setText(it.businesslogic.ireport.util.I18n.getString("delete", "Delete"));
        jMenuItemDelete.setEnabled(false);
        jMenuItemDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemDeleteActionPerformed(evt);
            }
        });

        jPopupMenuFields.add(jMenuItemDelete);

        jPopupMenuFields.add(jSeparator2);

        //Modified by Felix Firgau for I18n on Feb 9th 2006
        jMenuItemRefresh.setText(it.businesslogic.ireport.util.I18n.getString("refresh", "Refresh"));
        jMenuItemRefresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemRefreshActionPerformed(evt);
            }
        });

        jPopupMenuFields.add(jMenuItemRefresh);

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

        jScrollPane1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jScrollPane1MouseClicked(evt);
            }
        });

        jLibraryTree.setDragEnabled(true);
        jLibraryTree.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLibraryTreeMouseClicked(evt);
            }
        });

        jScrollPane1.setViewportView(jLibraryTree);

        add(jScrollPane1, java.awt.BorderLayout.CENTER);

    }// </editor-fold>//GEN-END:initComponents

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

        SubDatasetDialog sdd = new SubDatasetDialog(Misc.frameFromComponent(this),true);
        sdd.setVisible(true);

    }//GEN-LAST:event_jMenuItemNewSubDatasetActionPerformed

    private void jMenuItemPasteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemPasteActionPerformed
        TreePath[] paths = jLibraryTree.getSelectionPaths();

        if (jrf == null) return;
        if (paths.length == 1)
        {
           if (paths[0].getLastPathComponent() instanceof DefaultMutableTreeNode)
           {

                SubDataset sd = jrf.getReport();

                if (paths[0].getPath().length >= 3)
                {
                    Object osd = ((DefaultMutableTreeNode)paths[0].getPath()[1]).getUserObject();
                    if (osd instanceof SubDataset)
                    {
                        sd = (SubDataset)osd;
                    }
                }

               ValuesDialog vd = MainFrame.getMainInstance().getValuesDialog();
               DefaultMutableTreeNode dmn = (DefaultMutableTreeNode)paths[0].getLastPathComponent();
               if ((dmn.getUserObject().equals(it.businesslogic.ireport.util.I18n.getString("gui.library.fields","Fields")) || dmn.getUserObject() instanceof JRField) && jrf.getMainFrame().getValuesDialog().getClipboardFields().size() > 0)
               {
                   vd.getValuesPanel().duplicateFields( vd.getClipboardFields(), sd );
               }
               if ((dmn.getUserObject().equals(it.businesslogic.ireport.util.I18n.getString("gui.library.variables","Variables")) || dmn.getUserObject() instanceof JRVariable) && jrf.getMainFrame().getValuesDialog().getClipboardVariables().size() > 0)
               {
                   vd.getValuesPanel().duplicateVariables( vd.getClipboardVariables(), sd );
               }
               if ((dmn.getUserObject().equals(it.businesslogic.ireport.util.I18n.getString("gui.library.parameters","Parameters")) || dmn.getUserObject() instanceof JRParameter) && jrf.getMainFrame().getValuesDialog().getClipboardParameters().size() > 0)
               {
                   vd.getValuesPanel().duplicateParameters( vd.getClipboardParameters(), sd );
               }
           }
        }

    }//GEN-LAST:event_jMenuItemPasteActionPerformed

    private void jMenuItemCopyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemCopyActionPerformed
       TreePath[] paths = jLibraryTree.getSelectionPaths();

       boolean clearedVariablesClipboard = false;
       boolean clearedParametersClipboard = false;
       boolean clearedFieldsClipboard = false;

        for (int i=0; i<paths.length && jrf != null; ++i)
        {
            ValuesDialog vd = MainFrame.getMainInstance().getValuesDialog();
            Report report = jrf.getReport();
            if (paths[i].getLastPathComponent() instanceof DefaultMutableTreeNode)
            {
                Object obj = ((DefaultMutableTreeNode)paths[i].getLastPathComponent()).getUserObject();
                if (obj instanceof JRVariable )
                {
                        if (!clearedVariablesClipboard)
                        {
                            clearedVariablesClipboard = true;
                            vd.getClipboardVariables().removeAllElements();
                        }
                        vd.getClipboardVariables().add( ((JRVariable)obj).cloneMe() );
                }
                if (obj instanceof JRField )
                {
                        if (!clearedFieldsClipboard)
                        {
                            clearedFieldsClipboard = true;
                            vd.getClipboardFields().removeAllElements();
                        }
                        vd.getClipboardFields().add( ((JRField)obj).cloneMe() );
                }
                if (obj instanceof JRParameter )
                {
                        if (!clearedParametersClipboard)
                        {
                            clearedParametersClipboard = true;
                            vd.getClipboardParameters().removeAllElements();
                        }
                        vd.getClipboardParameters().add( ((JRParameter)obj).cloneMe() );
                }
            }
        }
    }//GEN-LAST:event_jMenuItemCopyActionPerformed

    private void jMenuItemCutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemCutActionPerformed
        TreePath[] paths = jLibraryTree.getSelectionPaths();

       boolean clearedVariablesClipboard = false;
       boolean clearedParametersClipboard = false;
       boolean clearedFieldsClipboard = false;

        for (int i=0; i<paths.length && jrf != null; ++i)
        {
            ValuesDialog vd = MainFrame.getMainInstance().getValuesDialog();
            Report report = jrf.getReport();

            SubDataset sd = report;

            if (paths[i].getPath().length == 4)
            {
                Object osd = ((DefaultMutableTreeNode)paths[i].getPath()[1]).getUserObject();
                if (osd instanceof SubDataset)
                {
                    sd = (SubDataset)osd;
                }
            }

            if (paths[i].getLastPathComponent() instanceof DefaultMutableTreeNode)
            {
                Object obj = ((DefaultMutableTreeNode)paths[i].getLastPathComponent()).getUserObject();
                if (obj instanceof JRVariable )
                {
                        if (!clearedVariablesClipboard)
                        {
                            clearedVariablesClipboard = true;
                            vd.getClipboardVariables().removeAllElements();
                        }
                        vd.getClipboardVariables().add( ((JRVariable)obj).cloneMe() );
                        sd.removeVariable((JRVariable)obj);
                }
                if (obj instanceof JRField )
                {
                        if (!clearedFieldsClipboard)
                        {
                            clearedFieldsClipboard = true;
                            vd.getClipboardFields().removeAllElements();
                        }
                        vd.getClipboardFields().add( ((JRField)obj).cloneMe() );
                        sd.removeField((JRField)obj);
                }
                if (obj instanceof JRParameter )
                {
                        if (!clearedParametersClipboard)
                        {
                            clearedParametersClipboard = true;
                            vd.getClipboardParameters().removeAllElements();
                        }
                        vd.getClipboardParameters().add( ((JRParameter)obj).cloneMe() );
                        sd.removeParameter((JRParameter)obj);
                }
            }
        }
    }//GEN-LAST:event_jMenuItemCutActionPerformed

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

        TreePath[] paths = jLibraryTree.getSelectionPaths();

        for (int i=0; i<paths.length && jrf != null; ++i)
        {
            Report report = jrf.getReport();
            SubDataset sd = report;

            try {
            if (paths[i].getPath().length == 4)
            {
                Object osd = ((DefaultMutableTreeNode)paths[i].getPath()[1]).getUserObject();
                if (osd instanceof SubDataset)
                {
                    sd = (SubDataset)osd;
                }
            }
            if (paths[i].getLastPathComponent() instanceof DefaultMutableTreeNode)
            {
                Object obj = ((DefaultMutableTreeNode)paths[i].getLastPathComponent()).getUserObject();
                if (obj instanceof JRVariable ) { sd.removeVariable((JRVariable)obj ); }
                if (obj instanceof JRField ) {  sd.removeField((JRField)obj ); }
                if (obj instanceof JRParameter ) {  sd.removeParameter((JRParameter)obj ); }
                if (obj instanceof SubDataset ) {

                    if (JOptionPane.showConfirmDialog(jLibraryTree, "Do you really want remove subDataset " + obj + " ?") == JOptionPane.OK_OPTION)
                    {
                        jrf.getReport().removeSubDataset((SubDataset)obj);
                    }
                }
            }
            } catch (Exception ex)
            {
                ex.printStackTrace();
            }
        }
    }//GEN-LAST:event_jMenuItemDeleteActionPerformed

    private void jMenuItemParameterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemParameterActionPerformed
         MainFrame.getMainInstance().getValuesDialog().getValuesPanel().newParameter(getSelectedSubDataset());
    }//GEN-LAST:event_jMenuItemParameterActionPerformed

    private void jMenuItemNewFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemNewFieldActionPerformed
         MainFrame.getMainInstance().getValuesDialog().getValuesPanel().newField(getSelectedSubDataset());
    }//GEN-LAST:event_jMenuItemNewFieldActionPerformed

    /**
     *   return the dataset to wich refer the current selection in the tree
     **/
    private SubDataset getSelectedSubDataset()
    {
        if (jrf == null) return null;

        SubDataset sd = jrf.getReport();
        TreePath[] paths = jLibraryTree.getSelectionPaths();
        if (paths.length == 1)
        {
           if (paths[0].getLastPathComponent() instanceof DefaultMutableTreeNode)
           {
                if (paths[0].getPath().length >= 2)
                {
                    Object osd = ((DefaultMutableTreeNode)paths[0].getPath()[1]).getUserObject();
                    if (osd instanceof SubDataset)
                    {
                        sd = (SubDataset)osd;
                    }
                }
           }
        }

        return sd;
    }


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

        // We have to use the same method used by ValuesDialog...
        MainFrame.getMainInstance().getValuesDialog().getValuesPanel().newVariable(getSelectedSubDataset());
    }//GEN-LAST:event_jMenuItemNewVariableActionPerformed

    private void jScrollPane1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jScrollPane1MouseClicked
       jLibraryTreeMouseClicked(evt);
    }//GEN-LAST:event_jScrollPane1MouseClicked

    private void jMenuItemRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemRefreshActionPerformed
        updateReportObjects();
    }//GEN-LAST:event_jMenuItemRefreshActionPerformed

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

        // We have to see what type of item we have selected...
        TreePath[] paths = jLibraryTree.getSelectionPaths();

        if (paths == null || paths.length == 0)
        {
            return;
        }

        if (paths.length == 1 && paths[0].getLastPathComponent() instanceof DefaultMutableTreeNode)
        {
            Object obj = ((DefaultMutableTreeNode)paths[0].getLastPathComponent()).getUserObject();
            if (obj instanceof JRVariable ) { MainFrame.getMainInstance().getValuesDialog().getValuesPanel().modifyVariable((JRVariable)obj ); }
            if (obj instanceof JRField ) { MainFrame.getMainInstance().getValuesDialog().getValuesPanel().modifyField((JRField)obj ); }
            if (obj instanceof JRParameter ) { MainFrame.getMainInstance().getValuesDialog().getValuesPanel().modifyParameter((JRParameter)obj ); }
            if (obj instanceof SubDataset ) {
                java.awt.Frame parent = Misc.frameFromComponent(this);
                SubDatasetDialog cd = new SubDatasetDialog(parent,true);
                cd.setSubDataset( (SubDataset)obj );
                cd.setVisible(true);
            }
        }
    }//GEN-LAST:event_jMenuItemEditActionPerformed

    private void jPopupMenuFieldsPopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_jPopupMenuFieldsPopupMenuWillBecomeVisible

        if (this.jrf != null)
        {
            jMenuAdd.setEnabled( true );
            jMenuItemRefresh.setEnabled( true );
        }
        else
        {
            jMenuItemCut.setEnabled(false);
            jMenuItemCopy.setEnabled(false);
            jMenuItemDelete.setEnabled(false);
            jMenuItemPaste.setEnabled(false);
            jMenuItemEdit.setEnabled(false);
            jMenuItemRefresh.setEnabled(false);
            jMenuAdd.setEnabled( false );
            return;
        }

        // Edit is able only if a single valid object is selected...
        TreePath[] paths = jLibraryTree.getSelectionPaths();

        if (paths == null || paths.length == 0)
        {
            jMenuItemCut.setEnabled(false);
            jMenuItemCopy.setEnabled(false);
            jMenuItemDelete.setEnabled(false);
            jMenuItemPaste.setEnabled(false);
            jMenuItemEdit.setEnabled(false);
            return;
        }

        if (paths.length == 1 &&
            paths[0].getLastPathComponent() instanceof DefaultMutableTreeNode &&
            ( (((DefaultMutableTreeNode)paths[0].getLastPathComponent()).getUserObject() instanceof JRField ) ||
              (((DefaultMutableTreeNode)paths[0].getLastPathComponent()).getUserObject() instanceof JRVariable ) ||
              (((DefaultMutableTreeNode)paths[0].getLastPathComponent()).getUserObject() instanceof JRParameter ) ||
              (((DefaultMutableTreeNode)paths[0].getLastPathComponent()).getUserObject() instanceof SubDataset )) )
        {
                  jMenuItemEdit.setEnabled(true);
        }
        else
        {
                  jMenuItemEdit.setEnabled( false );
        }

         if (paths.length > 0)
         {
             jMenuItemCut.setEnabled(true);
             jMenuItemCopy.setEnabled(true);
             jMenuItemDelete.setEnabled(true);
         }
         else
         {
             jMenuItemCut.setEnabled(false);
             jMenuItemCopy.setEnabled(false);
             jMenuItemDelete.setEnabled(false);
         }

        jMenuItemPaste.setEnabled(false);

         // If the only selection is the node "parameters"...
        if (paths.length == 1)
        {
           if (paths[0].getLastPathComponent() instanceof DefaultMutableTreeNode)
           {
               DefaultMutableTreeNode dmn = (DefaultMutableTreeNode)paths[0].getLastPathComponent();
               if ((dmn.getUserObject().equals(it.businesslogic.ireport.util.I18n.getString("gui.library.fields","Fields")) || dmn.getUserObject() instanceof JRField) && jrf.getMainFrame().getValuesDialog().getClipboardFields().size() > 0)
               {
                   jMenuItemPaste.setEnabled(true);
               }
               if ((dmn.getUserObject().equals(it.businesslogic.ireport.util.I18n.getString("gui.library.variables","Variables")) || dmn.getUserObject() instanceof JRVariable) && jrf.getMainFrame().getValuesDialog().getClipboardVariables().size() > 0)
               {
                   jMenuItemPaste.setEnabled(true);
               }
               if ((dmn.getUserObject().equals(it.businesslogic.ireport.util.I18n.getString("gui.library.parameters","Parameters")) || dmn.getUserObject() instanceof JRParameter) && jrf.getMainFrame().getValuesDialog().getClipboardParameters().size() > 0)
               {
                   jMenuItemPaste.setEnabled(true);
               }
           }
        }
    }//GEN-LAST:event_jPopupMenuFieldsPopupMenuWillBecomeVisible

    private void jLibraryTreeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLibraryTreeMouseClicked

        if (evt.getClickCount() == 1 && evt.getButton() == evt.BUTTON3)
        {
            jLibraryTree.setSelectionPath( jLibraryTree.getPathForLocation(evt.getX(), evt.getY() ) );
            jPopupMenuFields.show( jLibraryTree, evt.getPoint().x, evt.getPoint().y);
        }
        if (evt.getClickCount() == 2 && evt.getButton() == evt.BUTTON1)
        {
            TreePath[] paths = jLibraryTree.getSelectionPaths();

            if (paths == null || paths.length == 0)
            {
                return;
            }

            if (paths.length == 1 && paths[0].getLastPathComponent() instanceof DefaultMutableTreeNode)
            {
                Object obj = ((DefaultMutableTreeNode)paths[0].getLastPathComponent()).getUserObject();
                if (obj instanceof SubDataset ) return;
            }

            jMenuItemEditActionPerformed(new java.awt.event.ActionEvent(this,0,""));
        }
    }//GEN-LAST:event_jLibraryTreeMouseClicked

    public void languageChanged(it.businesslogic.ireport.util.LanguageChangedEvent evt) {

        fieldsNode.setUserObject(  it.businesslogic.ireport.util.I18n.getString("gui.library.fields","Fields"));
        variablesNode.setUserObject(  it.businesslogic.ireport.util.I18n.getString("gui.library.variables","Variables"));
        parametersNode.setUserObject(  it.businesslogic.ireport.util.I18n.getString("gui.library.parameters","Parameters"));
        jLibraryTree.updateUI();
    }

    public void setJReportFrame(JReportFrame jrf)
    {
       this.jrf = jrf;
       updateReportObjects();

       updateSubDatasets();

    }

    private void loadCustomObjects()
    {

    }
    private void loadSystemObjects()
    {
          DefaultMutableTreeNode root = (DefaultMutableTreeNode)jLibraryTree.getModel().getRoot();
          root.add(new DefaultMutableTreeNode(new PageNumberObject() ));
          root.add(new DefaultMutableTreeNode(new TotalPagesObject() ));
          root.add(new DefaultMutableTreeNode(new PageXYObject() ));
          root.add(new DefaultMutableTreeNode(new TotalObject() ));
          root.add(new DefaultMutableTreeNode(new DateObject() ));
          root.add(new DefaultMutableTreeNode(new PercentageObject() ));
    }

    private void addLibraryObject(String folder, AbstractLibraryObject obj)
    {
        DefaultMutableTreeNode root = (DefaultMutableTreeNode)jLibraryTree.getModel().getRoot();
        if (folder == null || folder.length() == 0)
        {
            root.add(new DefaultMutableTreeNode(new PageNumberObject() ));
        }
        else
        {
            // Look for folder...
            Enumeration enum_childrens = root.children();
            while (enum_childrens.hasMoreElements())
            {
                DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)enum_childrens.nextElement();
                if ( (""+dmtn.getUserObject()).equalsIgnoreCase(folder ) )
                {
                    dmtn.add(new DefaultMutableTreeNode( obj ));
                }
            }
        }
    }

    public void updateReportObjects()
    {
       this.fieldsNode.removeAllChildren();
       this.parametersNode.removeAllChildren();
       this.variablesNode.removeAllChildren();

       if (jrf == null) {

           jLibraryTree.updateUI();
           return;
       }

       java.util.Enumeration e = jrf.getReport().getFields().elements();
       while (e.hasMoreElements())
       {
             fieldsNode.add(new DefaultMutableTreeNode(e.nextElement()));
       }
        e = jrf.getReport().getParameters().elements();
       while (e.hasMoreElements())
       {
             parametersNode.add(new DefaultMutableTreeNode(e.nextElement()));
       }

        e = jrf.getReport().getVariables().elements();
       while (e.hasMoreElements())
       {
             variablesNode.add(new DefaultMutableTreeNode(e.nextElement()));
       }

       jLibraryTree.updateUI();
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTree jLibraryTree;
    private javax.swing.JMenu jMenuAdd;
    private javax.swing.JMenuItem jMenuItemCopy;
    private javax.swing.JMenuItem jMenuItemCut;
    private javax.swing.JMenuItem jMenuItemDelete;
    private javax.swing.JMenuItem jMenuItemEdit;
    private javax.swing.JMenuItem jMenuItemNewField;
    private javax.swing.JMenuItem jMenuItemNewSubDataset;
    private javax.swing.JMenuItem jMenuItemNewVariable;
    private javax.swing.JMenuItem jMenuItemParameter;
    private javax.swing.JMenuItem jMenuItemPaste;
    private javax.swing.JMenuItem jMenuItemRefresh;
    private javax.swing.JPopupMenu jPopupMenuFields;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    // End of variables declaration//GEN-END:variables

     public void subDatasetObjectChanged(it.businesslogic.ireport.gui.event.SubDatasetObjectChangedEvent evt)
     {
         if (evt != null && evt.getSource() instanceof Report)
         {
            this.updateReportObjects();
         }
         else
         {
             updateSubDatasetNode( evt.getSource() );
         }
     }

    public void reportSubDatasetChanged(it.businesslogic.ireport.gui.event.ReportSubDatasetChangedEvent evt) {

        DefaultMutableTreeNode root = (DefaultMutableTreeNode)jLibraryTree.getModel().getRoot();
        if (evt.getAction() == evt.ADDED &&
           evt.getObjectType() == evt.OBJECT_SUBDATASET)
       {
           int lastDatasourceIndex = 3;
           for (lastDatasourceIndex=3; root.getChildCount() > lastDatasourceIndex; lastDatasourceIndex++)
           {
               if ( ((DefaultMutableTreeNode)root.getChildAt(lastDatasourceIndex)).getUserObject() instanceof SubDataset) continue;
               break;
           }

           for (int i=0; i<evt.getElements().size(); ++i)
           {
            DefaultMutableTreeNode subDatasetNode = new DefaultMutableTreeNode(evt.getElements().elementAt(i));
            root.insert(subDatasetNode, lastDatasourceIndex);
            updateSubDatasetNode( subDatasetNode );
            lastDatasourceIndex++;
           }
       } else if (evt.getAction() == evt.REMOVED &&
           evt.getObjectType() == evt.OBJECT_SUBDATASET)
       {

            DefaultMutableTreeNode subDatasetNode = null;
             for (int i=0; i<evt.getElements().size(); ++i)
             {
                // 1. Find the datasource...
                 for (int k=0; k< root.getChildCount(); ++k)
                 {
                     if (((DefaultMutableTreeNode)root.getChildAt(k)).getUserObject() == evt.getElements().elementAt(i))
                     {
                         root.remove(k);
                         break;
                     }
                 }
             }

           jLibraryTree.updateUI();

       } else if (evt.getAction() == evt.CHANGED &&
           evt.getObjectType() == evt.OBJECT_SUBDATASET)
       {
           jLibraryTree.updateUI();
       }
    }


    public void updateSubDatasetNode(SubDataset subDataset)
    {
        DefaultMutableTreeNode root = (DefaultMutableTreeNode)jLibraryTree.getModel().getRoot();
        for (int k=0; k< root.getChildCount(); ++k)
        {
             if (((DefaultMutableTreeNode)root.getChildAt(k)).getUserObject() == subDataset)
             {
                 updateSubDatasetNode((DefaultMutableTreeNode)root.getChildAt(k));
                 return;
             }
        }

    }

    public void updateSubDatasetNode(DefaultMutableTreeNode subDatasetNode )
    {
        DefaultMutableTreeNode dsFieldsNode = null;
        DefaultMutableTreeNode dsVariablesNode = null;
        DefaultMutableTreeNode dsParametersNode = null;

        SubDataset subDataset = (SubDataset)subDatasetNode.getUserObject();

        if (subDatasetNode.getChildCount() == 0)
        {
            dsFieldsNode = new DefaultMutableTreeNode(it.businesslogic.ireport.util.I18n.getString("gui.library.fields","Fields"),true);
            subDatasetNode.add( dsFieldsNode );

            dsVariablesNode = new DefaultMutableTreeNode(it.businesslogic.ireport.util.I18n.getString("gui.library.variables","Variables"),true);
            subDatasetNode.add( dsVariablesNode );

            dsParametersNode = new DefaultMutableTreeNode(it.businesslogic.ireport.util.I18n.getString("gui.library.parameters","Parameters"),true);
            subDatasetNode.add( dsParametersNode );
        }
        else
        {
            dsFieldsNode = (DefaultMutableTreeNode)subDatasetNode.getChildAt(0);
            dsVariablesNode = (DefaultMutableTreeNode)subDatasetNode.getChildAt(1);
            dsParametersNode = (DefaultMutableTreeNode)subDatasetNode.getChildAt(2);
        }

        dsFieldsNode.removeAllChildren();
        dsVariablesNode.removeAllChildren();
        dsParametersNode.removeAllChildren();

        java.util.Enumeration e = subDataset.getFields().elements();
        while (e.hasMoreElements())
        {
             dsFieldsNode.add(new DefaultMutableTreeNode(e.nextElement()));
        }
        e = subDataset.getParameters().elements();
        while (e.hasMoreElements())
        {
             dsParametersNode.add(new DefaultMutableTreeNode(e.nextElement()));
       }

        e = subDataset.getVariables().elements();
       while (e.hasMoreElements())
       {
             dsVariablesNode.add(new DefaultMutableTreeNode(e.nextElement()));
       }

       jLibraryTree.updateUI();
    }

    public void updateSubDatasets()
    {
        DefaultMutableTreeNode root = (DefaultMutableTreeNode)jLibraryTree.getModel().getRoot();
        for (int k=0; k< root.getChildCount(); ++k)
        {
             if (((DefaultMutableTreeNode)root.getChildAt(k)).getUserObject() instanceof SubDataset)
             {
                 root.remove(k);
                 k--;
             }
        }

        if (jrf != null)
        {
            int lastDatasourceIndex = 3;
            for (int i=0; i< jrf.getReport().getSubDatasets().size(); ++i)
            {
                DefaultMutableTreeNode subDatasetNode = new DefaultMutableTreeNode(jrf.getReport().getSubDatasets().elementAt(i));
                root.insert(subDatasetNode, lastDatasourceIndex);
                updateSubDatasetNode( subDatasetNode );
                lastDatasourceIndex++;
            }
        }

        jLibraryTree.updateUI();
    }
}
