/**
 * File:    NewViewWizard.java
 * Created: 13.03.2009
 *
/*******************************************************************************
 * Copyright (c) 2005-2011
 * University of Augsburg, Germany, http://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:
 *    Melanie Hesselbart, Programming distributed Systems Lab, University of Augsburg 
 *    	- initial API and implementation
 *******************************************************************************/
package org.eclipse.jwt.we_view_editor.wizards;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.eclipse.core.runtime.*;
import org.eclipse.jface.operation.*;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jwt.we_view_editor.Activator;
import org.eclipse.jwt.we_view_editor.PluginProperties;
import org.eclipse.jwt.we.misc.views.ViewEcoreManager;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.emf.common.ui.URIEditorInput;
import org.eclipse.emf.common.util.URI;
import org.eclipse.ui.*;
import org.eclipse.ui.ide.IDE;


/**
 * Creates a new view-file.
 */

public class NewViewWizard
		extends Wizard
		implements INewWizard
{

	/**
	 * The page in the wizard where project, view-name and file-name must be set.
	 */
	private NewViewWizardPage page;

	/**
	 * Necessary for init() ...
	 */
	private ISelection selection;


	/**
	 * The constructor.
	 */
	public NewViewWizard()
	{
		super();
		setNeedsProgressMonitor(true);
	}


	/**
	 * Adding the page to the wizard.
	 */
	public void addPages()
	{
		page = new NewViewWizardPage(selection);
		addPage(page);
	}


	/**
	 * Ending the wizard by the Finish-button.
	 */
	public boolean performFinish()
	{
		final String containerName = page.getContainerName();
		final String fileName = page.getFileName();
		ViewEcoreManager.getInstance().setName(page.getViewnameText());

		IRunnableWithProgress op = new IRunnableWithProgress()
		{

			public void run(IProgressMonitor monitor) throws InvocationTargetException
			{
				try
				{
					doFinish(containerName, fileName, monitor);
				}
				catch (CoreException e)
				{
					throw new InvocationTargetException(e);
				}
				finally
				{
					monitor.done();
				}
			}
		};

		try
		{
			getContainer().run(true, false, op);
		}
		catch (InterruptedException e)
		{
			return false;
		}
		catch (InvocationTargetException e)
		{
			Throwable realException = e.getTargetException();
			MessageDialog.openError(getShell(), PluginProperties.newWizard_error,
					realException.getMessage());

			return false;
		}

		return true;
	}


	/**
	 * This method creates the file.
	 */
	private void doFinish(String containerName, String fileName, IProgressMonitor monitor)
			throws CoreException
	{
		// create a sample file
		monitor.beginTask(PluginProperties.newWizard_creating + fileName, 2);
		IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();

		final Object file;

		if (!containerName.equals(""))
		{
			IResource resource = root.findMember(new Path(containerName));

			if (!resource.exists() || !(resource instanceof IContainer))
			{
				throwCoreException(PluginProperties.newWizard_projectDoesntExist_part1
						+ "\"" + //$NON-NLS-1$
						"\"" + PluginProperties.newWizard_projectDoesntExist_part2); //$NON-NLS-1$
			}

			IContainer container = (IContainer) resource;
			file = container.getFile(new Path(fileName));
		}
		else
		{
			file = new File(URI.createFileURI(fileName).toFileString());
		}

		monitor.worked(1);
		monitor.setTaskName(PluginProperties.newWizard_openFileForEditing);
		getShell().getDisplay().asyncExec(new Runnable()
		{

			public void run()
			{
				IWorkbenchPage page = PlatformUI.getWorkbench()
						.getActiveWorkbenchWindow().getActivePage();

				if (file instanceof IFile)
				{
					try
					{
						IDE.openEditor(page, (IFile) file, true);
					}
					catch (PartInitException e)
					{
					}
				}
				else
				{
					URI fileUri = URI.createFileURI(((File) file).getAbsolutePath());
					IEditorDescriptor editorDescriptor = null;
					try
					{
						editorDescriptor = PlatformUI.getWorkbench().getEditorRegistry()
								.getDefaultEditor(fileUri.toString());

						if (editorDescriptor == null)
						{
							return;
						}

						PlatformUI.getWorkbench().getActiveWorkbenchWindow()
								.getActivePage().openEditor(new URIEditorInput(fileUri),
										editorDescriptor.getId());
					}
					catch (final Exception e)
					{
						return;
					}

				}
			}
		});

		monitor.worked(1);
	}


	/**
	 * Throws a core exception.
	 * 
	 * @param message
	 * @throws CoreException
	 */
	private void throwCoreException(String message) throws CoreException
	{
		IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.OK,
				message, null);
		throw new CoreException(status);
	}


	/**
	 * Inits the wizard.
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection)
	{
		this.selection = selection;
	}
}