/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.jaspersoft.ireport.designer.resourcebundle;

import java.awt.BorderLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.Serializable;
import java.util.logging.Logger;
import javax.swing.ActionMap;
import javax.swing.SwingUtilities;
import javax.swing.text.DefaultEditorKit;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.ExplorerUtils;
import org.openide.explorer.view.BeanTreeView;
import org.openide.explorer.view.TreeView;
import org.openide.filesystems.FileAttributeEvent;
import org.openide.filesystems.FileChangeListener;
import org.openide.filesystems.FileEvent;
import org.openide.filesystems.FileRenameEvent;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;
import org.openide.loaders.DataObjectNotFoundException;
import org.openide.nodes.FilterNode;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.lookup.AbstractLookup;
import org.openide.util.lookup.InstanceContent;
import org.openide.util.lookup.ProxyLookup;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
//import org.openide.util.Utilities;

/**
 * Top component which displays something.
 */
final class ResourceBundleTopComponent extends TopComponent implements LookupListener, ExplorerManager.Provider, PropertyChangeListener, FileChangeListener {

    private static ResourceBundleTopComponent instance;

    transient protected TreeView view;

    /** Dynamic Lookup content */
    private final InstanceContent ic;
    /** Lookup instance */
    private final Lookup lookup;
    /** validity flag */
    transient private boolean valid = true;
    private final ExplorerManager manager = new ExplorerManager();

    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";

    private static final String PREFERRED_ID = "ResourceBundleTopComponent";

    private final Lookup.Result <DataObject> result;

    private ResourceBundleTopComponent() {
        initComponents();

        this.ic = new InstanceContent();
        this.lookup = new AbstractLookup(ic);

        ActionMap map = getActionMap();
        map.put(DefaultEditorKit.copyAction, ExplorerUtils.actionCopy(manager));
        map.put(DefaultEditorKit.cutAction, ExplorerUtils.actionCut(manager));
        map.put(DefaultEditorKit.pasteAction, ExplorerUtils.actionPaste(manager));
        map.put("delete", ExplorerUtils.actionDelete(manager, true));

        associateLookup( new ProxyLookup(lookup, ExplorerUtils.createLookup(manager, map)) );

        setLayout(new BorderLayout());
        view = new BeanTreeView();
        //view.setRootVisible(false);
        add(view, BorderLayout.CENTER);

        setName(NbBundle.getMessage(ResourceBundleTopComponent.class, "CTL_ResourceBundleTopComponent"));
        setToolTipText(NbBundle.getMessage(ResourceBundleTopComponent.class, "HINT_ResourceBundleTopComponent"));
//        setIcon(Utilities.loadImage(ICON_PATH, true));
        result = Utilities.actionsGlobalContext().lookup(new Lookup.Template(DataObject.class));
        result.addLookupListener(this);
        result.allItems();
        resultChanged(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() {

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link #findInstance}.
     */
    public static synchronized ResourceBundleTopComponent getDefault() {
        if (instance == null) {
            instance = new ResourceBundleTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the ResourceBundleTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized ResourceBundleTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(ResourceBundleTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof ResourceBundleTopComponent) {
            return (ResourceBundleTopComponent) win;
        }
        Logger.getLogger(ResourceBundleTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID +
                "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    /** replaces this in object stream */
    @Override
    public Object writeReplace() {
        return new ResolvableHelper();
    }

    @Override
    protected String preferredID() {
        return PREFERRED_ID;
    }

    /**
     * @return the dataObject
     */
    public

    DataObject getDataObject() {
        return dataObject;
    }

    /**
     * @param dataObject the dataObject to set
     */
    public void setDataObject(DataObject dataObject) {
        this.dataObject = dataObject;
    }

    final static class ResolvableHelper implements Serializable {

        private static final long serialVersionUID = 1L;

        public Object readResolve() {
            return ResourceBundleTopComponent.getDefault();
        }
    }

    private DataObject dataObject = null;
    public void resultChanged(LookupEvent arg0) {

        if (!result.allInstances().isEmpty())
        {
            DataObject dobj = result.allInstances().iterator().next();
            if (dobj == dataObject) return;
            
            if (getDataObject() != null)
            {
                getDataObject().removePropertyChangeListener(this);
                getDataObject().getPrimaryFile().getParent().removeFileChangeListener(this);
            }
          
            setDataObject(dobj);
            if (getDataObject() != null)
            {
                try {
                    DataObject.find(getDataObject().getPrimaryFile().getParent());
                } catch (DataObjectNotFoundException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
            final DataObject nDO = getDataObject();
            
            getDataObject().addPropertyChangeListener(this);

            getExplorerManager().setRootContext(nDO.getNodeDelegate());
            view.setRootVisible(true);
        }
//        else
//        {
//            getExplorerManager().setRootContext(new AbstractNode(Children.LEAF));
//            view.setRootVisible(false);
//        }
    }

    public ExplorerManager getExplorerManager() {
        return manager;
    }

    public void propertyChange(PropertyChangeEvent evt) {

        if (evt != null)
        {
            System.out.println("Data changed: " + evt.getPropertyName());
            System.out.flush();
        }
        /*
        final DataObject nDO = getDataObject();
        if (nDO != null)
        {
            SwingUtilities.invokeLater(new Runnable() {

                public void run()
                {
                    getExplorerManager().setRootContext(nDO.getNodeDelegate());
                }
            });
        }
        */
    }

    public void fileFolderCreated(FileEvent arg0) {
    }

    public void fileDataCreated(FileEvent evt) {
        if (getDataObject() != null)
        {
            System.out.println("Locale added...?" + getDataObject().getNodeDelegate().getChildren());
            System.out.flush();
            //FileUtil.refreshFor( FileUtil.toFile(evt.getFile()) );
        }
    }

    public void fileChanged(FileEvent arg0) {
    }

    public void fileDeleted(FileEvent evt) {
        System.out.println("Locale deleted...?");
        System.out.flush();
        if (getDataObject() != null)
        {
            //FileUtil.refreshFor( FileUtil.toFile(evt.getFile()) );
        }
        //propertyChange(null);
    }



    public void fileRenamed(FileRenameEvent arg0) {
        //propertyChange(null);
    }

    public void fileAttributeChanged(FileAttributeEvent arg0) {
    }



}
