/*
 * iReport - Visual Designer for JasperReports.
 * Copyright (C) 2002 - 2013 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 part of iReport.
 *
 * iReport is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * iReport is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with iReport. If not, see <http://www.gnu.org/licenses/>.
 */
package com.jaspersoft.ireport.jasperserver.ui;

import com.jaspersoft.ireport.designer.IRLocalJasperReportsContext;
import com.jaspersoft.ireport.designer.IReportManager;
import com.jaspersoft.ireport.designer.ThreadUtils;
import com.jaspersoft.ireport.designer.tools.JrxmlPreviewToolbar;
import java.awt.BorderLayout;
import java.awt.Graphics2D;
import java.io.Serializable;
import java.util.logging.Logger;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.swing.JRViewerController;
import net.sf.jasperreports.swing.JRViewerPanel;
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.
 */
final public class JRViewerTopComponent extends TopComponent {

    private static JRViewerTopComponent instance;
    /** 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 = "JRViewerTopComponent";
    
    
    JRViewerController viewerContext = new JRViewerController(IRLocalJasperReportsContext.getInstance(), null, null);
    JrxmlPreviewToolbar viewerToolbar = new JrxmlPreviewToolbar(viewerContext);
    
    JRViewerPanel viewerPanel = null;
    

    private JRViewerTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(JRViewerTopComponent.class, "CTL_JRViewerTopComponent"));
        setToolTipText(NbBundle.getMessage(JRViewerTopComponent.class, "HINT_JRViewerTopComponent"));
//        setIcon(Utilities.loadImage(ICON_PATH, true));
        
    }
    
    
//    public void setJasperPrint(JasperPrint print)
//    {
//        JRViewer viewer = new JRViewer(print);
//        this.removeAll();
//        this.add(viewer, BorderLayout.CENTER);
//        this.updateUI();
//        
//    }
        
    public void setJasperPrint(final JasperPrint print)
    {
        ThreadUtils.invokeInAWTThread( new Runnable()
        {
            public void run()
            {
                removeAll();
        
                if (print != null)
                {
                    if (viewerPanel == null)
                    {
                        viewerPanel = new JRViewerPanel(viewerContext)
                        {
                            protected void paintPage(Graphics2D grx) 
                            {
                                ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); 
                                try
                                {
                                    Thread.currentThread().setContextClassLoader(IReportManager.getJRExtensionsClassLoader());
                                    super.paintPage(grx);
                                }
                                finally
                                {
                                    Thread.currentThread().setContextClassLoader(oldClassLoader);
                                }
                            }
                        };
                    }
                        
                    add(viewerPanel, BorderLayout.CENTER);
                    add(viewerToolbar, BorderLayout.NORTH);
                    
                    viewerToolbar.init();
                    
                    viewerContext.loadReport(print);
                    viewerContext.refreshPage();
                    viewerPanel.updateUI();
                }
                updateUI();
                
            }
        });
        
    }


    /** 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 JRViewerTopComponent getDefault() {
        if (instance == null) {
            instance = new JRViewerTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the JRViewerTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized JRViewerTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(JRViewerTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof JRViewerTopComponent) {
            return (JRViewerTopComponent) win;
        }
        Logger.getLogger(JRViewerTopComponent.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;
    }

    final static class ResolvableHelper implements Serializable {

        private static final long serialVersionUID = 1L;

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