//------------------------------------------------------------------------------
// Copyright (c) 2005, 2006 IBM Corporation and others.
// 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:
// IBM Corporation - initial implementation
//------------------------------------------------------------------------------
package org.eclipse.epf.rcp;

import java.io.IOException;

import org.eclipse.core.runtime.IPlatformRunnable;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.osgi.service.datalocation.Location;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;

/**
 * This class controls all aspects of the application's execution.
 * 
 * @author Kelvin Low
 * @since 1.0
 */
public class MainApplication implements IPlatformRunnable {

	/*
	 * @see org.eclipse.core.runtime.IPlatformRunnable#run(java.lang.Object)
	 */
	public Object run(Object args) throws Exception {
		Display display = PlatformUI.createDisplay();
		Shell shell = new Shell(display, SWT.ON_TOP);
		try {
			boolean noLock = false;
			String[] rmcArgs = Platform.getApplicationArgs();
			for (int i = 0; i < rmcArgs.length; i++) {
				if (rmcArgs[i].equalsIgnoreCase("-nolock")) { //$NON-NLS-1$
					noLock = true;
				}
			}

			if (!noLock && !checkWorkspaceLock(shell)) {
				Platform.endSplash();
				return EXIT_OK;
			}

			int returnCode = PlatformUI.createAndRunWorkbench(display,
					new MainWorkbenchAdvisor());
			if (returnCode == PlatformUI.RETURN_RESTART) {
				return IPlatformRunnable.EXIT_RESTART;
			}
			return IPlatformRunnable.EXIT_OK;
		} finally {
			if (shell != null)
				shell.dispose();
			display.dispose();
		}
	}

	protected boolean checkWorkspaceLock(Shell shell) {
		Location workspaceLocation = Platform.getInstanceLocation();
		String appName = Platform.getProduct().getName();
		try {
			if (workspaceLocation.lock()) {
				return true;
			}
			MessageDialog.openInformation(shell, NLS.bind(RCPResources.workspaceCannotLockTitle, appName), //$NON-NLS-1$
					NLS.bind(RCPResources.workspaceCannotLockMessage, appName)); 
		} catch (IOException e) {
			MainPlugin.getDefault().getLogger().logError(
					NLS.bind(RCPResources.workspaceCannotLockMessage, appName), 
					e);
			MessageDialog.openInformation(shell, NLS.bind(RCPResources.workspaceCannotLockTitle, appName), //$NON-NLS-1$
					e.getMessage());
		}
		return false;

	}

}
