package net.sourceforge.javydreamercsw.client.ui.components.project.explorer;

import java.awt.BorderLayout;
import java.beans.PropertyVetoException;
import java.util.Collection;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sourceforge.javydreamercsw.client.ui.nodes.AbstractVMBeanNode;
import net.sourceforge.javydreamercsw.client.ui.nodes.ProjectChildFactory;
import net.sourceforge.javydreamercsw.client.ui.nodes.RootNode;
import net.sourceforge.javydreamercsw.client.ui.nodes.capability.RefreshableCapability;
import org.netbeans.api.db.explorer.DatabaseConnection;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.ExplorerUtils;
import org.openide.explorer.view.BeanTreeView;
import org.openide.nodes.Node;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.util.Utilities;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
        dtd = "-//net.sourceforge.javydreamercsw.client.ui//Main//EN",
        autostore = false)
@TopComponent.Description(
        preferredID = "ProjectExplorerTopComponent",
        iconBase = "net/sourceforge/javydreamercsw/client/ui/VSmall.png",
        persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "explorer", openAtStartup = true)
@ActionID(category = "Window", id
        = "net.sourceforge.javydreamercsw.client.ui.ProjectExplorerTopComponent")
@ActionReference(path = "Menu/Window", position = 333)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_ProjectExplorerAction",
        preferredID = "ProjectExplorerTopComponent")
@Messages({
    "CTL_ProjectExplorerAction=Project Explorer",
    "CTL_ProjectExplorerTopComponent=Project Explorer",
    "HINT_ProjectExplorerTopComponent=Project Explorer Window"
})
public final class ProjectExplorerComponent extends TopComponent
        implements ExplorerManager.Provider, LookupListener {

    private final ExplorerManager mgr = new ExplorerManager();
    private static DatabaseConnection conn;
    private Lookup.Result<RefreshableCapability> result = null;
    private static AbstractVMBeanNode currentNode;
    private static final Logger LOG
            = Logger.getLogger(ProjectExplorerComponent.class.getSimpleName());

    public ProjectExplorerComponent() {
        initComponents();
        setName(Bundle.CTL_ProjectExplorerTopComponent());
        setToolTipText(Bundle.HINT_ProjectExplorerTopComponent());
        setLayout(new BorderLayout());
        add(new BeanTreeView(), BorderLayout.CENTER);
        associateLookup(ExplorerUtils.createLookup(getExplorerManager(),
                getActionMap()));
        RootNode root = new RootNode(new ProjectChildFactory());
        getExplorerManager().setRootContext(root);
        try {
            getExplorerManager().setSelectedNodes(new Node[]{root});
        } catch (PropertyVetoException ex) {
            Exceptions.printStackTrace(ex);
        }
    }

    /**
     * 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() {

        treePane = new javax.swing.JScrollPane();

        treePane.setEnabled(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(treePane, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(treePane, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private static javax.swing.JScrollPane treePane;
    // End of variables declaration//GEN-END:variables

    @Override
    public void componentOpened() {
        ExplorerUtils.activateActions(getExplorerManager(), true);
        result = Utilities.actionsGlobalContext().lookupResult(RefreshableCapability.class);
        result.allItems();
        result.addLookupListener(this);
    }

    @Override
    public void componentClosed() {
        ExplorerUtils.activateActions(getExplorerManager(), false);
        result.removeLookupListener(this);
        result = null;
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    @Override
    public ExplorerManager getExplorerManager() {
        return mgr;
    }

    /**
     * @return the conn
     */
    public static DatabaseConnection getConnection() {
        treePane.setEnabled(conn != null);
        return conn;
    }

    /**
     * @param conn the conn to set
     */
    public static void setConnection(DatabaseConnection connection) {
        conn = connection;
    }

    public static void refresh() {
        if (currentNode != null) {
            LOG.log(Level.FINE, "Refreshing: {0}", currentNode);
            currentNode.refresh();
        }
    }

    @Override
    public void resultChanged(LookupEvent le) {
        Lookup.Result res = (Lookup.Result) le.getSource();
        Collection instances = res.allInstances();

        if (!instances.isEmpty()) {
            Iterator it = instances.iterator();
            while (it.hasNext()) {
                Object item = it.next();
                if (item instanceof AbstractVMBeanNode) {
                    AbstractVMBeanNode p = (AbstractVMBeanNode) item;
                    currentNode = p;
                    for (RefreshableCapability refresh : currentNode.getLookup().lookupAll(RefreshableCapability.class)) {
                        refresh.refresh();
                    }
                }
            }
        }
    }
}

@@ -679,81 +679,8 @@
 es;%0A
-import org.openide.awt.ActionID;%0Aimport org.openide.awt.ActionReference;%0A
 impo
@@ -1562,179 +1562,8 @@
 ue)%0A
-@ActionID(category = %22Window%22, id%0A        = %22net.sourceforge.javydreamercsw.client.ui.ProjectExplorerTopComponent%22)%0A@ActionReference(path = %22Menu/Window%22, position = 333)%0A
 @Top

Remove action from menu.