/**
 * File:    Plugin.java
 * Created: 26.11.2005
 *
 *
/*******************************************************************************
 * Copyright (c) 2005-2011
 * University of Augsburg, Germany <www.ds-lab.org>
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Markus Bauer, Programming distributed Systems Lab, University of Augsburg 
 *    	- initial API and implementation
 *******************************************************************************/

package org.eclipse.jwt.we;

import java.util.logging.ConsoleHandler;

import org.eclipse.emf.common.ui.EclipseUIPlugin;
import org.eclipse.emf.common.ui.URIEditorInput;
import org.eclipse.emf.common.util.URI;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jwt.we.misc.logging.Logger;
import org.eclipse.jwt.we.misc.logging.internal.EclipseLogHandler;
import org.eclipse.jwt.we.misc.logging.internal.TextFormatter;
import org.eclipse.jwt.we.misc.views.Views;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.osgi.framework.BundleContext;

/**
 * The main plugin class to be used in the desktop.
 * 
 * @version $Id: Plugin.java,v 1.15 2010-05-10 08:23:24 chsaad Exp $
 * @author Markus Bauer (markusbauer@users.sourceforge.net), Programming
 *         distributed Systems Lab, University of Augsburg, Germany,
 *         www.ds-lab.org
 */
public class Plugin extends EclipseUIPlugin
{

	/**
	 * The Logger.
	 */
	private static final Logger logger = Logger.getLogger(Plugin.class);

	/**
	 * The shared instance.
	 */
	private static Plugin plugin;

	/**
	 * Path where the icons are located
	 */
	public static final String ICONS_BASE_PATH = "icons/"; //$NON-NLS-1$


	/**
	 * The constructor.
	 * 
	 * It initialised the {@link EclipseLogHandler} to forward warning to the
	 * eclipse error log. The singleton instance is stored.
	 */
	public Plugin()
	{
		// set console handler.
		// This does not work from the properties file, because the classloader
		// uses by Sun is not able to find the classes. And it is not possible
		// to
		// change the Sun code to use the eclipse classloader.
		final java.util.logging.Logger packageLogger = java.util.logging.Logger
				.getLogger(Plugin.class.getPackage().getName());
		final ConsoleHandler handler = new ConsoleHandler();
		handler.setFormatter(new TextFormatter());
		packageLogger.addHandler(handler);

		// Set eclipse log handler to forward warnings and errors to the eclipse
		// error log.
		final EclipseLogHandler eclipseLogHandler = new EclipseLogHandler(this);
		packageLogger.addHandler(eclipseLogHandler);

		logger.instanceCreation();
		plugin = this;
	}


	/**
	 * This method is called upon plug-in activation
	 * 
	 * @param context
	 *            The bundle context for this plug-in.
	 * @throws Exception
	 *             If this plug-in did not start up properly
	 */
	@Override
	public void start(final BundleContext context) throws Exception
	{
		super.start(context);
		logger.debug("Plugin started."); //$NON-NLS-1$
	}


	/**
	 * This method is called when the plug-in is stopped
	 * 
	 * @param context
	 *            The bundle context for this plug-in.
	 * @throws Exception
	 *             If this method fails to shut down this plug-in.
	 */
	@Override
	public void stop(final BundleContext context) throws Exception
	{
		super.stop(context);
		plugin = null;
		logger.debug("Plugin stopped."); //$NON-NLS-1$
	}


	/**
	 * @return The ID of this plugin.
	 */
	public static String getId()
	{
		if (getInstance() == null)
		{
			logger.info("Return a static plugin id, because the plugin is not yet " //$NON-NLS-1$
					+ "created. It may be different from the actual plugin id."); //$NON-NLS-1$
			return Plugin.class.getPackage().getName();
		}
		return getInstance().getBundle().getSymbolicName();
	}


	/**
	 * @return The shared instance.
	 */
	public static Plugin getInstance()
	{
		return plugin;
	}


	/**
	 * This one is called primarily by the WEPreferences for the creation of a
	 * preference page.
	 * 
	 * @return The shared instance.
	 */
	public static Plugin getDefault()
	{
		return plugin;
	}


	/**
	 * @return Returns the factoryRegistry singleton.
	 */
	public IFactoryRegistry getFactoryRegistry()
	{
		return Views.getInstance().getSelectedView().getFactoryRegistry();
	}


	/**
	 * Opens a file in its editor.
	 * 
	 * @param workbench
	 *            The workbench.
	 * @param fileUri
	 *            The file to open.
	 * @return <code>true</code>, if the file was open sucessfully.
	 *         <code>false</code> if an error occured.
	 */
	public static boolean openEditor(final IWorkbench workbench, final URI fileUri)
	{
		// get window and page
		final IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
		final IWorkbenchPage page = workbenchWindow.getActivePage();

		// get the editor descriptor
		IEditorDescriptor editorDescriptor = null;
		try
		{
			editorDescriptor = workbench.getEditorRegistry().getDefaultEditor(
					fileUri.toString());

			if (editorDescriptor == null)
			{
				MessageDialog.openError(workbenchWindow.getShell(),
						PluginProperties.editor_ErrorMessage_title, PluginProperties
								.editor_WarnNoEditor_message(fileUri.toString()));
				return false;
			}
		}
		catch (final Exception e)
		{
			MessageDialog.openError(workbenchWindow.getShell(),
					PluginProperties.editor_ErrorOpenEditor_title, PluginProperties
							.editor_WarnNoEditor_message(fileUri.toString()));
			return false;
		}

		// open the editor
		try
		{
			page.openEditor(new URIEditorInput(fileUri), editorDescriptor.getId());
		}
		catch (final PartInitException exception)
		{
			MessageDialog
					.openError(workbenchWindow.getShell(),
							PluginProperties.editor_ErrorOpenEditor_title, exception
									.getMessage());
			return false;
		}

		return true;
	}
}
