/**
 * File:    CreationWizard1.java
 * Created: 29.05.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:
 *    Christian Saad, Programming distributed Systems Lab, University of Augsburg 
 *    	- initial API and implementation
 *    Marc Blachon, Bull SAS, Grenoble, France
 *      - getting ImageFactory from factory registry.
 *******************************************************************************/

package org.eclipse.jwt.we.misc.wizards.creation;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jwt.meta.model.core.Model;
import org.eclipse.jwt.we.Plugin;
import org.eclipse.jwt.we.PluginProperties;
import org.eclipse.jwt.we.editors.WEEditor;
import org.eclipse.jwt.we.misc.logging.Logger;
import org.eclipse.jwt.we.misc.views.Views;
import org.eclipse.jwt.we.misc.wizards.WizardHelper;
import org.eclipse.jwt.we.misc.wizards.template.imp.ImportTemplateWizardPage;
import org.eclipse.jwt.we.model.view.Diagram;
import org.eclipse.jwt.we.model.view.impl.ViewFactoryImpl;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;


/**
 * This is a wizard for creating a new model file. It supports the import of template
 * files.
 * 
 * This wizard does NOT offer the possibility to include the created model file in a
 * existing project.
 * 
 * @version $Id: CreationWizard1.java,v 1.12 2009-12-17 09:50:50 chsaad Exp $
 * @author Christian Saad (csaad@gmx.net), Programming distributed Systems Lab, University
 *         of Augsburg, Germany, www.ds-lab.org
 */

public class CreationWizard1
		extends Wizard
		implements INewWizard
{

	/**
	 * A Logger.
	 */
	static final Logger logger = Logger.getLogger(CreationWizard1.class);

	/**
	 * The page for the template import
	 */
	protected ImportTemplateWizardPage importTemplatePage;

	/**
	 * This is the initial object creation page.
	 */
	protected CreationWizardPageFileName selectFilenamePage;

	/**
	 * Remember the workbench during initialization.
	 */
	protected IWorkbench workbench;

	/**
	 * The URI of the new file.
	 */
	protected URI newFileURI;


	/**
	 * This just records the information.
	 * 
	 * @param workbench
	 *            The current workbench.
	 * @param selection
	 *            The current object selection.
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection)
	{
		this.workbench = workbench;
		setWindowTitle(PluginProperties.menu_WE_item);
		setDefaultPageImageDescriptor(Plugin.getInstance().getFactoryRegistry()
				.getImageFactory(Views.getInstance().getSelectedView())
				.createImageDescriptor(PluginProperties.editor_Wizard_icon));
	}


	/**
	 * The framework calls this to create the contents of the wizard.
	 */
	@Override
	public void addPages()
	{
		selectFilenamePage = new CreationWizardPageFileName("filename_page1", true); //$NON-NLS-1$
		selectFilenamePage.setTitle(PluginProperties.menu_WE_item);
		selectFilenamePage.setDescription(PluginProperties.editor_Wizard_description);
		addPage(selectFilenamePage);

		importTemplatePage = new ImportTemplateWizardPage("template_page1", workbench); //$NON-NLS-1$
		importTemplatePage.setTitle(PluginProperties.wizards_ImportTemplateWizard_title);
		importTemplatePage.setDescription(PluginProperties.wizards_ImportSelect_label);
		importTemplatePage.setCreationMode(true);
		addPage(importTemplatePage);
	}


	/**
	 * Get the URI from the page.
	 * 
	 * @return The entered URI.
	 */
	public URI getModelURI()
	{
		return selectFilenamePage.getFileURI();
	}


	/**
	 * Get the package name from the page.
	 * 
	 * @return The package name.
	 */
	public String getPackageName()
	{
		return selectFilenamePage.getPackageName();
	}


	/**
	 * Get the activity name from the page.
	 * 
	 * @return The package name.
	 */
	public String getActivityName()
	{
		return selectFilenamePage.getActivityName();
	}


	/**
	 * @return The entered author.
	 */
	public String getAuthor()
	{
		return selectFilenamePage.getAuthor();
	}


	/**
	 * @return The entered version.
	 */
	public String getVersion()
	{
		return selectFilenamePage.getVersion();
	}


	/**
	 * Get the standard package state.
	 * 
	 * @return The standard package state.
	 */
	public boolean getStandardPackages()
	{
		return selectFilenamePage.getStandardPackages();
	}


	/**
	 * Get the template list from the page.
	 * 
	 * @return The list of templates.
	 */
	public ArrayList getTemplates()
	{
		return importTemplatePage.getTemplates();
	}


	/**
	 * Returns the URI of the new file.
	 * 
	 * @return The file URI.
	 */
	public URI getNewFileURI()
	{
		return newFileURI;
	}


	/**
	 * Sets the URI of the new File.
	 * 
	 * @param newFileURI
	 */
	public void setNewFileURI(URI newFileURI)
	{
		this.newFileURI = newFileURI;
	}


	/**
	 * Do the work after everything is specified.
	 * 
	 * @return <code>true</code>, if the wizards completes successfully.
	 *         <code>false</code> if an error occurred or the dialog was canceled.
	 */
	@Override
	public boolean performFinish()
	{
		try
		{
			// Get the URI of the model file.
			String filename = getModelURI().toFileString();
			if (!filename.endsWith(WEEditor.getWorkflowExtension()))
			{
				filename += "." + WEEditor.getWorkflowExtension(); //$NON-NLS-1$
			}
			final File newfile = new File(filename);
			final URI fileWorkflowUri = URI.createFileURI(filename);
			if (newfile.exists())
			{
				if (!MessageDialog.openQuestion(getShell(),
						PluginProperties.editor_QuestionOverwriteFile_title,
						PluginProperties.bind(
								PluginProperties.editor_QuestionOverwriteFile_message,
								newfile.getAbsolutePath())))
				{
					selectFilenamePage.selectFileField();
					return false;
				}
			}

			// get the URI for the diagram
			final URI fileDiagramUri = fileWorkflowUri.trimFileExtension()
					.appendFileExtension(WEEditor.getDiagramExtension());

			// Do the work within an operation.
			@SuppressWarnings("unchecked")
			IRunnableWithProgress operation = new IRunnableWithProgress()
			{

				public void run(IProgressMonitor progressMonitor)
				{
					try
					{
						ResourceSet resourceSet = new ResourceSetImpl();

						// create the resources
						Resource resourceWorkflow = resourceSet
								.createResource(fileWorkflowUri);
						Resource resourceDiagram = resourceSet
								.createResource(fileDiagramUri);

						// add the initial model object to the contents.
						EObject rootObject = WizardHelper.createResources(
								getPackageName(), getActivityName(), getAuthor(),
								getVersion(), getStandardPackages(), getTemplates());
						if (rootObject != null)
						{
							resourceWorkflow.getContents().add(rootObject);
						}

						// add the initial diagram object to the contents.
						Diagram diagramData = ViewFactoryImpl.eINSTANCE.createDiagram();
						diagramData.setDescribesModel((Model) rootObject);
						resourceDiagram.getContents().add(diagramData);

						// Save the contents of the resource to the file system.
						Map options = new HashMap();
						options.put(XMLResource.OPTION_ENCODING, "UTF-8"); //$NON-NLS-1$
						resourceWorkflow.save(options);
						resourceDiagram.save(options);
					}
					catch (Exception exception)
					{
						logger.warning(exception);
					}
					finally
					{
						progressMonitor.done();
					}
				}
			};

			getContainer().run(false, false, operation);

			// set the URI
			setNewFileURI(fileWorkflowUri);

			// open the newly created file
			Plugin.openEditor(PlatformUI.getWorkbench(), newFileURI);

			return true;
		}
		catch (Exception exception)
		{
			logger.warning(exception);
			return false;
		}
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.jface.wizard.Wizard#dispose()
	 */
	@Override
	public void dispose()
	{
		super.dispose();
		workbench = null;
	}

}
