/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.netbeans.modules.websvc.core.webservices.ui.panels;

import java.awt.AWTEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.tree.TreeSelectionModel;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ui.OpenProjects;

import org.openide.DialogDescriptor;
import org.openide.ErrorManager;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.view.BeanTreeView;
import org.openide.filesystems.FileObject;
import org.openide.loaders.DataObject;
import org.openide.loaders.DataObjectNotFoundException;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.nodes.FilterNode;
import org.openide.nodes.Node;
import org.openide.util.NbBundle;

/**
 *
 * @author rico
 */
public class ProjectFileExplorer extends JPanel implements ExplorerManager.Provider, PropertyChangeListener {

    private DialogDescriptor descriptor;
    private final ExplorerManager manager;
    private BeanTreeView treeView;
    private DataObject selectedFolder;
    private final Project[] projects;
    private final Children rootChildren;
    private final Node explorerClientRoot;
    private final List<Node> projectNodeList;

    public ProjectFileExplorer() {
        projects = OpenProjects.getDefault().getOpenProjects();
        rootChildren = new Children.Array();
        explorerClientRoot = new AbstractNode(rootChildren);
        projectNodeList = new ArrayList<Node>();
        manager = new ExplorerManager();

        initComponents();
        initUserComponents();
    }

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

        dontCopyCB = new javax.swing.JCheckBox();
        jLblTreeView = new javax.swing.JLabel();

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

        org.openide.awt.Mnemonics.setLocalizedText(dontCopyCB, org.openide.util.NbBundle.getMessage(ProjectFileExplorer.class, "TXT_DONOTCOPY")); // NOI18N
        dontCopyCB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dontCopyCBActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(11, 11, 0, 11);
        add(dontCopyCB, gridBagConstraints);

        org.openide.awt.Mnemonics.setLocalizedText(jLblTreeView, org.openide.util.NbBundle.getMessage(ProjectFileExplorer.class, "LBL_SelectProjectLocation")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(11, 11, 0, 11);
        add(jLblTreeView, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents

private String getTreeViewLabel(boolean dontCopy){
    if(dontCopy){
        return NbBundle.getMessage(ProjectFileExplorer.class, "TXT_DONOTCOPY_TOOLTIP"); // NOI18N
    }
    return NbBundle.getMessage(ProjectFileExplorer.class, "LBL_SelectProjectLocation"); // NOI18N
}

private void dontCopyCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dontCopyCBActionPerformed
    if (dontCopyCB.isSelected()) {
        descriptor.setValid(true);
        treeView.setEnabled(false);
        jLblTreeView.setText(getTreeViewLabel(true));
        eventBlocker.setVisible(true);
    } else {
        descriptor.setValid(getSelectedFile() != null);
        treeView.setEnabled(true);
        jLblTreeView.setText(getTreeViewLabel(false));
        eventBlocker.setVisible(false);
    }
}//GEN-LAST:event_dontCopyCBActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox dontCopyCB;
    private javax.swing.JLabel jLblTreeView;
    // End of variables declaration//GEN-END:variables
    private void initUserComponents() {
        treeView = new BeanTreeView();
        treeView.setRootVisible(false);
        treeView.setPopupAllowed(false);
        treeView.setDefaultActionAllowed(false);
        treeView.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

        java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(11, 11, 0, 11);
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        eventBlocker.setOpaque(false);
        eventBlocker.setVisible(dontCopyCB.isSelected());
        add(eventBlocker, gridBagConstraints);
        add(treeView, gridBagConstraints);
        jLblTreeView.setLabelFor(treeView.getViewport().getView());
        treeView.getAccessibleContext().setAccessibleName(NbBundle.getMessage(ClientExplorerPanel.class, "ACSD_AvailableWebServicesTree")); // NOI18N
        treeView.getAccessibleContext().setAccessibleDescription(NbBundle.getMessage(ClientExplorerPanel.class, "ACSD_AvailableWebServicesTree")); // NOI18N
        dontCopyCB.setToolTipText(NbBundle.getMessage(ProjectFileExplorer.class, "TXT_DONOTCOPY_TOOLTIP")); // NOI18N
    }

    /** Component used to block mouse events to treeView when "Do not copy" check-box is selected. */
    private final JPanel eventBlocker = new JPanel() {
        {
            enableEvents(AWTEvent.MOUSE_EVENT_MASK);
        }
    };

    // Needed because eventBlocker overlaps with treeView
    @Override
    public boolean isOptimizedDrawingEnabled() {
        return false;
    }

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

    @Override
    public void addNotify() {
        super.addNotify();
        manager.addPropertyChangeListener(this);
        for (int i = 0; i < projects.length; i++) {
            try {
                Project project = projects[i];
                FileObject projectDir = project.getProjectDirectory();
                DataObject projectDirDObj = DataObject.find(projectDir);
                Node rootNode = projectDirDObj.getNodeDelegate();
                FilterNode node = new FilterNode(rootNode);
                projectNodeList.add(node);

            } catch (DataObjectNotFoundException ex) {
                ErrorManager.getDefault().notify(ex);
            }
        }
        Node[] projectNodes = new Node[projectNodeList.size()];
        projectNodeList.<Node>toArray(projectNodes);
        rootChildren.add(projectNodes);
        manager.setRootContext(explorerClientRoot);

        descriptor.setValid(false);
    }

    @Override
    public void removeNotify() {
        manager.removePropertyChangeListener(this);
        super.removeNotify();
    }

    public void setDescriptor(DialogDescriptor descriptor) {
        this.descriptor = descriptor;
    }

    public boolean dontCopy(){
        return dontCopyCB.isSelected();
    }
     public DataObject getSelectedFolder() {
          return selectedFolder;
      }
     
     private DataObject getSelectedFile(){
         Node nodes[] = manager.getSelectedNodes();
         if(nodes != null && nodes.length > 0){
             Node node = nodes[0];
             DataObject dobj = node.getLookup().lookup(DataObject.class);
             if(dobj != null){
                 if(dobj.getPrimaryFile().isFolder()){
                     return dobj;
                 }
             }
         }
         return null;
     }
     
    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        if (evt.getSource() == manager) {
            if (ExplorerManager.PROP_SELECTED_NODES.equals(evt.getPropertyName())) {
                DataObject folder = getSelectedFile();
                if(folder != null){
                    selectedFolder = folder;
                    descriptor.setValid(true);
                }else{
                    selectedFolder = null;
                    descriptor.setValid(false);
                }
            }
        }
    }
}
