/*
 * Copyright (C) 2005 - 2007 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 General Public License version 2 as published by
 * the Free Software Foundation.
 *
 * This program is distributed WITHOUT ANY WARRANTY; and without the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see http://www.gnu.org/licenses/gpl.txt
 * or write to:
 *
 * Free Software Foundation, Inc.,
 * 59 Temple Place - Suite 330,
 * Boston, MA  USA  02111-1307
 *
 *
 *
 *
 * LibraryPanel.java
 * 
 * Created on 14 settembre 2004, 23.49
 *
 */

package it.businesslogic.ireport.gui.library;
import it.businesslogic.ireport.gui.event.ReportSubDatasetChangedEvent;
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.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() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jLibraryTree = new javax.swing.JTree();

        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

    /**
     *   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 != null && 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 jScrollPane1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jScrollPane1MouseClicked
       jLibraryTreeMouseClicked(evt);
    }//GEN-LAST:event_jScrollPane1MouseClicked

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

    }//GEN-LAST:event_jLibraryTreeMouseClicked

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

         jLibraryTree.updateUI();
    }

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

    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.JScrollPane jScrollPane1;
    // 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();
//    }
 
     
     
    public void applyI18n(){
                // Start autogenerated code ----------------------
                // End autogenerated code ----------------------
    }
    
    public void setSelectedObject( Object obj)
    {
        DefaultMutableTreeNode mtd = Misc.findNodeWithUserObject( obj, (TreeNode)this.jLibraryTree.getModel().getRoot() );
    
        if (mtd != null)
        {
            TreePath path = new TreePath( mtd.getPath() );
            jLibraryTree.setSelectionPath( path );
            jLibraryTree.scrollPathToVisible( path );
        }
    }

    public void reportSubDatasetChanged(ReportSubDatasetChangedEvent evt) {
        
    }
    

}
