/**
 * File:    GeneralHelper.java
 * Created: 29.11.2006
 *
 *
/*******************************************************************************
 * 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:
 *   Wolf Fischer, Programming distributed Systems Lab, University of Augsburg 
 *    	- initial API and implementation
 *    Marc Blachon, Bull SAS, Grenoble, France
 *      - adding getObjectClass() method.
 *******************************************************************************/

package org.eclipse.jwt.we.misc.util;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.jwt.we.Plugin;
import org.eclipse.jwt.we.editors.WEEditor;
import org.eclipse.jwt.we.editors.preferences.wrappers.ColorPreferenceWrapper;
import org.eclipse.jwt.we.editors.preferences.wrappers.FontPreferenceWrapper;
import org.eclipse.jwt.we.misc.extensions.ExtensionsHelper;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.osgi.framework.Bundle;

/**
 * Some static helper methods
 * 
 * @version $Id: GeneralHelper.java,v 1.20 2010-06-10 14:16:24 chsaad Exp $
 * @author Wolf Fischer, Programming distributed Systems Lab, University of
 *         Augsburg, Germany, www.ds-lab.org
 */
public class GeneralHelper
{

	/**
	 * This list holds instances of all opened {@link WEEditor} instances for
	 * refreshing purposes.
	 */
	private static List<WEEditor> editorinstances = new ArrayList<WEEditor>();

	/**
	 * Save editor during its initialization process.
	 */
	private static WEEditor initializingEditor;

	/**
	 * Active unit test mode to suppress dialogs.
	 */
	private static boolean jUnitMode = false;


	/**
	 * Set a reference to an initializing editor (unset after initialization has
	 * finished in createPages).
	 * 
	 * @param initializingEditor
	 *            The initializingEditor to set.
	 */
	public static void setInitializingEditor(WEEditor initializingEditor)
	{
		GeneralHelper.initializingEditor = initializingEditor;
	}


	/**
	 * Returns the currently active instance of the editor or null, if there is
	 * none.
	 * 
	 * IMPORTANT: USE ONLY IF SURE THAT THE *ACTIVE* INSTANCE IS NEEDED. THE
	 * CURRENT INSTANCE MAY DIFFER FROM THE ACTIVE INSTANCE!!
	 * 
	 * If in doubt, use getInstanceForEObject()
	 * 
	 * @return The active editor.
	 */
	public static WEEditor getActiveInstance()
	{
		Plugin instance = Plugin.getInstance();

		// return an editor during its startup phase when it is not yet
		// available through
		// the workbench
		if (initializingEditor != null)
		{
			return initializingEditor;
		}

		// get the active workbench window
		IWorkbenchWindow workbenchwindow = instance.getWorkbench()
				.getActiveWorkbenchWindow();
		if (workbenchwindow == null)
		{
			return null;
		}

		// get the active page
		IWorkbenchPage activepage = workbenchwindow.getActivePage();
		if (activepage == null)
		{
			return null;
		}

		// get the active editor of the active page
		if (activepage.getActiveEditor() instanceof WEEditor)
		{
			return (WEEditor) activepage.getActiveEditor();
		}
		else
		{
			return null;
		}
	}


	/**
	 * Returns the Workflow Editor for a given EObject.
	 * 
	 * @param eobject
	 * @return
	 */
	public static WEEditor getInstanceForEObject(EObject eobject)
	{
		if (eobject == null)
		{
			return null;
		}

		for (WEEditor ed : getEditors())
		{
			if (eobject.eResource().getResourceSet().equals(
					ed.getMainModelResource().getResourceSet()))
			{
				return ed;
			}
		}

		return null;
	}


	/**
	 * Returns the currently active shell or null, if there is none.
	 * 
	 * @return The active shell.
	 */
	public static Shell getActiveShell()
	{
		Plugin instance = Plugin.getInstance();
		IWorkbench iwb = instance.getWorkbench();
		if (iwb == null)
			return null;
		IWorkbenchWindow iwbw = iwb.getActiveWorkbenchWindow();
		if (iwbw == null)
			return null;
		Shell shell = iwbw.getShell();
		if (shell == null)
			return null;
		return shell;
	}


	/**
	 * Returns true if JWT runs in plugin mode, false if in RCP mode (AgilPro
	 * support).
	 * 
	 * @return The active shell.
	 */
	public static boolean isPluginMode()
	{
		if (Platform.getProduct() == null
				|| (Platform.getProduct().getName() != null && (Platform.getProduct()
						.getName().toLowerCase().contains("rcp") || Platform.getProduct().getName().toLowerCase().contains("limo")))) //$NON-NLS-1$ //$NON-NLS-2$
		{
			return false;
		}
		else
		{
			return true;
		}
	}


	/**
	 * Get JUnit mode activated?
	 * 
	 * @return
	 */
	public static boolean isjUnitMode()
	{
		return jUnitMode;
	}


	/**
	 * Set JUnit mode to suppress dialogs.
	 * 
	 * @param jUnitMode
	 */
	public static void setJUnitMode(boolean jUnitMode)
	{
		GeneralHelper.jUnitMode = jUnitMode;
	}


	/**
	 * Is used by the WEEditor to register itself at the views manager
	 * 
	 * @param ed
	 *            An instance of the editor
	 */
	public static void registerEditor(WEEditor ed)
	{
		editorinstances.add(ed);
	}


	/**
	 * Deletes an WEEditor instance from the internal instance list.
	 * 
	 * @param ed
	 *            the instance of the WEEditor to be removed
	 */
	public static void deregisterEditor(WEEditor ed)
	{
		editorinstances.remove(ed);

		// dispose gid resources
		if (editorinstances.size() == 0)
		{
			Plugin.getDefault().getImageRegistry().dispose();
			FontPreferenceWrapper.disposeFonts();
			ColorPreferenceWrapper.disposeColors();
		}
	}


	/**
	 * Returns a list of all editors
	 * 
	 * @return The editors.
	 */
	public static List<WEEditor> getEditors()
	{
		return editorinstances;
	}


	/**
	 * Reads the WE version from the bundle version. Important: The official
	 * AgilPro version differs from this version in that its first number is 1
	 * higher (e.g. jwt 0.5.0 = agilpro 1.5.0).
	 * 
	 * @return The WE version
	 */
	public static String getWEVersion()
	{
		Bundle weBundle = Plugin.getInstance().getBundle();
		String version = (String) weBundle.getHeaders().get(
				org.osgi.framework.Constants.BUNDLE_VERSION);
		String[] versionItems = version.split("\\."); //$NON-NLS-1$
		if (versionItems.length > 3)
		{
			version = versionItems[0] + "." + versionItems[1] + "." + versionItems[2]; //$NON-NLS-1$ //$NON-NLS-2$
		}
		return version;
	}


	/**
	 * Ask the user to switch to the Workflow Editor perspective.
	 */
	public static void switchToWEPerspective()
	{
		IConfigurationElement element = ExtensionsHelper.findConfigurationElement(
				"org.eclipse.ui.newWizards", //$NON-NLS-1$
				"org.eclipse.jwt.we.wizards.export.CreationWizard2"); //$NON-NLS-1$

		org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard
				.updatePerspective(element);
	}


	/**
	 * Returns the class of the object
	 * 
	 * @param modelObject
	 * @return the object class
	 */
	public static Class getObjectClass(Object modelObject)
	{
		if (modelObject instanceof EObject)
		{
			// use the instance class of the eclass of the eobject
			return ((EObject) modelObject).eClass().getInstanceClass();
		}
		else if (modelObject instanceof EClass)
		{
			// use the instance class of the eclass
			return ((EClass) modelObject).getInstanceClass();
		}
		else if (modelObject instanceof Class)
		{
			// use the class
			return (Class) modelObject;
		}
		else if (modelObject != null)
		{
			// use the object class
			return modelObject.getClass();
		}

		return null;
	}

}
