/**
 * File:    PreviewViewConfWizardPage.java
 * Created: 16.12.2008
 *
 *
/*******************************************************************************
 * 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
 *******************************************************************************/

package org.eclipse.jwt.we.misc.wizards.view.pages;

import java.util.Set;

import org.eclipse.draw2d.LightweightSystem;
import org.eclipse.draw2d.Viewport;
import org.eclipse.draw2d.parts.Thumbnail;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.gef.LayerConstants;
import org.eclipse.gef.editparts.ScalableFreeformRootEditPart;
import org.eclipse.gef.ui.parts.GraphicalViewerImpl;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.jwt.we.PluginProperties;
import org.eclipse.jwt.we.editors.pages.activityEditor.WEEditorSheet;
import org.eclipse.jwt.we.editors.pages.activityEditor.internal.IActivityEditor;
import org.eclipse.jwt.we.editors.preferences.PreferenceReader;
import org.eclipse.jwt.we.misc.logging.Logger;
import org.eclipse.jwt.we.misc.util.EMFHelper;
import org.eclipse.jwt.we.misc.util.GeneralHelper;
import org.eclipse.jwt.we.misc.wizards.WizardHelper;
import org.eclipse.jwt.we.misc.wizards.view.ViewConfWizard;
import org.eclipse.jwt.meta.model.processes.Activity;
import org.eclipse.jwt.we.parts.JWTEditPartFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IWorkbench;


/**
 * A preview for the imported layout view data.
 * 
 * @version $Id: PreviewViewConfWizardPage.java,v 1.3 2009-11-26 12:41:26 chsaad Exp $
 * @author Christian Saad (csaad@gmx.net), Programming distributed Systems Lab, University
 *         of Augsburg, Germany, www.ds-lab.org
 */
public class PreviewViewConfWizardPage
		extends WizardPage
{

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

	/**
	 * The available activities.
	 */
	private Combo activityCombo;

	/**
	 * The canvas for the preview.
	 */
	private Canvas previewCanvas;

	/**
	 * The thumbnail.
	 */
	private Thumbnail thumbnail;

	/**
	 * The graphical viewer.
	 */
	private GraphicalViewerImpl gv;
	
	
	/**
	 * Constructor.
	 * 
	 * @param pageId
	 *            The name of the page.
	 * @param workbench
	 *            The workbench.
	 */
	public PreviewViewConfWizardPage(String pageId, IWorkbench workbench)
	{
		super(pageId);
	}


	/**
	 * @return The EMF EditingDomain.
	 */
	public EditingDomain getEditingDomain()
	{
		return (EditingDomain) GeneralHelper.getActiveInstance().getAdapter(
				EditingDomain.class);
	}


	/**
	 * @return The {@link AdapterFactory} from an {@link AdapterFactoryEditingDomain} if
	 *         available.
	 */
	public AdapterFactory getAdapterFactory()
	{
		return (AdapterFactory) GeneralHelper.getActiveInstance().getAdapter(
				AdapterFactory.class);
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite
	 * )
	 */
	public void createControl(Composite parent)
	{
		// Composite
		final Composite composite = new Composite(parent, SWT.NONE);
		composite.setLayout(new GridLayout(2, false));
		composite.setLayoutData(WizardHelper.createData(GridData.FILL, GridData.FILL,
				true, false, -1, -1));

		// Label
		Label activityLabel = new Label(composite, SWT.LEFT);
		activityLabel.setText(PluginProperties.wizards_ViewConfPreviewSelect_label);
		activityLabel.setLayoutData(WizardHelper.createData(-1, -1, false, false, 1, 1));

		// Activity Combo Box
		activityCombo = new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY);
		activityLabel.setLayoutData(WizardHelper.createData(-1, -1, false, false, 1, 1));
		Set availableElements = EMFHelper
				.collectRelevantElements((EObject) GeneralHelper.getActiveInstance()
						.getModel());
		for (Object object : availableElements)
		{
			if (((EObject) object) instanceof Activity)
			{
				String activityName = ""; //$NON-NLS-1$
				if (((Activity) object).getName() != null)
				{
					activityName = ((Activity) object).getName();
				}
				activityCombo.add(activityName);
				activityCombo.setData(activityName, object);
			}
		}

		// Preview Canvas
		previewCanvas = new Canvas(composite, SWT.NONE);
		previewCanvas.setBackground(PreferenceReader.appearanceEditorColor.get());
		previewCanvas.setLayoutData(WizardHelper.createData(GridData.FILL, GridData.FILL,
				true, true, 1, 2));

		// combo listener
		activityCombo.addSelectionListener(new SelectionListener()
		{

			public void widgetDefaultSelected(SelectionEvent e)
			{
			}


			public void widgetSelected(SelectionEvent e)
			{
				loadPreview();
			}
		});

		// load first preview
		if (activityCombo.getItemCount() > 0)
		{
			activityCombo.select(0);
			loadPreview();
		}

		// Validate
		setMessage(null);
		setControl(composite);

		// refresh packageviewer display
		getShell().pack();

		// make dialog bigger and center
		WizardHelper.resizeDialog(getShell());
	}


	/**
	 * Load the preview.
	 */
	private void loadPreview()
	{
		// if an activity is selected
		if (activityCombo.getItemCount() > 0 && activityCombo.getSelectionIndex() > -1)
		{
			// the selected activity
			Activity selectedActivity = (Activity) activityCombo.getData(activityCombo
					.getText());

			ScalableFreeformRootEditPart rootEditPart = null;

			if (GeneralHelper.getActiveInstance().getOpenActivities().contains(
					selectedActivity))
			{
				// if the activity is already displayed in a graphical viewer...
				IActivityEditor activityEditor = GeneralHelper.getActiveInstance()
						.getPageForActivity(selectedActivity);
				if (activityEditor instanceof WEEditorSheet)
				{
					rootEditPart = ((WEEditorSheet) activityEditor).getRootEditPart();
				}
			}
			else
			{
				// ...if not, create a new graphical viewer
				if (gv != null)
				{
					gv.setEditDomain(null);
					gv.setEditPartFactory(null);
					gv.getControl().dispose();
				}

				gv = new GraphicalViewerImpl();
				gv.createControl(previewCanvas);
				gv.setRootEditPart(new ScalableFreeformRootEditPart());
				gv.setEditPartFactory(new JWTEditPartFactory());
				gv.setEditDomain(GeneralHelper.getActiveInstance().getEditDomain());
				gv.setContents(activityCombo.getData(activityCombo.getText()));
				rootEditPart = (ScalableFreeformRootEditPart) gv.getRootEditPart();
				rootEditPart.getFigure().setBackgroundColor(
						PreferenceReader.appearanceEditorColor.get());
			}

			// set the contents of the thumbnail
			if (rootEditPart != null)
			{
				if (thumbnail != null)
				{
					// deactivate old thumbnail
					thumbnail.deactivate();
					previewCanvas.redraw();
				}
				thumbnail = new Thumbnail((Viewport) rootEditPart.getFigure());
				thumbnail.setSource(rootEditPart
						.getLayer(LayerConstants.PRINTABLE_LAYERS));

				// create lws
				LightweightSystem lws = new LightweightSystem(previewCanvas);
				lws.setContents(thumbnail);
			}
		}
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.jface.wizard.WizardPage#getNextPage()
	 */
	@Override
	public IWizardPage getNextPage()
	{
		// update preview layout data on entering the preview page
		((ViewConfWizard)getWizard()).updatePreview();

		// this is the last page
		return null;
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite
	 * )
	 */
	@Override
	public void dispose()
	{
		if (gv != null)
		{
			gv.setEditDomain(null);
			gv.setEditPartFactory(null);
			gv.getControl().dispose();
		}

		if (activityCombo != null && !activityCombo.isDisposed())
		{
			activityCombo.dispose();
			activityCombo = null;
		}

		if (previewCanvas != null && !previewCanvas.isDisposed())
		{
			previewCanvas.dispose();
			previewCanvas = null;
		}

		if (thumbnail != null)
		{
			thumbnail.deactivate();
			thumbnail = null;
		}

		super.dispose();
	}

}