/*
 * 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.java.navigation;

import java.awt.BorderLayout;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingUtilities;
import org.netbeans.api.java.source.ui.ElementJavadoc;
import org.openide.filesystems.FileObject;
import org.openide.util.ImageUtilities;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.openide.util.Utilities;

/**
 * Top component which displays something.
 * 
 * @author Sandip V. Chitale (Sandip.Chitale@Sun.Com)
 */
public final class JavadocTopComponent extends TopComponent {
    
    private static final Logger LOGGER = Logger.getLogger(JavadocTopComponent.class.getName());
    
    private static JavadocTopComponent instance;
    /** path to the icon used by the component and its open action */
    public static final String ICON_PATH = "org/netbeans/modules/java/navigation/resources/javadoc_action.png";
    
    private static final String PREFERRED_ID = "JavadocTopComponent";
    
    private DocumentationScrollPane documentationPane;
    
    private JavadocTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(JavadocTopComponent.class, "CTL_JavadocTopComponent"));
        setToolTipText(NbBundle.getMessage(JavadocTopComponent.class, "HINT_JavadocTopComponent"));
        setIcon(ImageUtilities.loadImage(ICON_PATH, true));
        
        documentationPane = new DocumentationScrollPane( false );
        add( documentationPane, BorderLayout.CENTER );
    }
    
    public void setJavadoc(
            final FileObject owner,
            final ElementJavadoc doc){
        LOGGER.log(Level.FINE, "Setting javadoc: {0}", doc);   //NOI18N
        documentationPane.setData(owner,  doc );
    }

    public void clearContent(
            final FileObject owner) {
        documentationPane.clearContent(owner);
    }
    
    public static boolean shouldUpdate() {
        if (!exists()) {
            LOGGER.fine("shouldUpdate -> false (no instance)"); //NOI18N
            return false;
        }
        else  {
            final boolean isShowing = instance.isShowing();
            LOGGER.log(Level.FINE, "shouldUpdate -> {0}", isShowing);   //NOI18N
            return isShowing;
        }
    }

    public static boolean exists() {
        return instance != 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() {

        setLayout(new java.awt.BorderLayout());
    }// </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 JavadocTopComponent getDefault() {
        if (instance == null) {
            instance = new JavadocTopComponent();
        }
        return instance;
    }
    
    /**
     * Obtain the JavadocTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized JavadocTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            LOGGER.log(Level.WARNING, 
                       "Cannot find MyWindow component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof JavadocTopComponent) {
            return (JavadocTopComponent)win;
        }
        LOGGER.log(Level./* Shut up! Logged dozens of times in every session. */FINE,
                "There seem to be multiple components with the '" + PREFERRED_ID +
                "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }
   
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    @Override
    protected void componentActivated() {
        super.componentActivated();
        // System.out.println("JDW Activated");
        documentationPane.getViewport().getView().requestFocusInWindow();
    }
    
    @Override
    public void componentOpened() {
        // System.out.println("JDW Opened ");
        documentationPane.getViewport().getView().requestFocusInWindow();
    }

    @Override
    protected void componentShowing() {
        super.componentShowing();
        // System.out.println("JDW Showing");
        CaretListeningFactory.runAgain();
    }
    
    
    
    public void componentClosed() {
    }
    
    /** replaces this in object stream */
    public Object writeReplace() {
        return new ResolvableHelper();
    }
    
    protected String preferredID() {
        return PREFERRED_ID;
    }
    
    static final class ResolvableHelper implements Serializable {
        private static final long serialVersionUID = 1L;
        public Object readResolve() {
            return JavadocTopComponent.getDefault();
        }
    }
    
}
