/**
 * File:    CreationWizardPageTemplate.java
 * Created: 10.02.2007
 *
 *
/*******************************************************************************
 * 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.template.imp;

import java.util.ArrayList;

import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.jwt.we.PluginProperties;
import org.eclipse.jwt.we.editors.WEEditor;
import org.eclipse.jwt.we.editors.actions.handlers.TemplateHandler;
import org.eclipse.jwt.we.misc.logging.Logger;
import org.eclipse.jwt.we.misc.util.GeneralHelper;
import org.eclipse.jwt.we.misc.wizards.WizardHelper;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.ui.IWorkbench;


/**
 * This is a wizard page where template files can be selected for the import into a new
 * model file.
 * 
 * @version $Id: CreationWizardPageTemplate.java
 * @author Christian Saad (csaad@gmx.net), Programming distributed Systems Lab, University
 *         of Augsburg, Germany, www.ds-lab.org
 */
public class ImportTemplateWizardPage
		extends WizardPage
{

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

	/**
	 * A viewer for the selected template.
	 */
	protected TreeViewer packageViewer;

	/**
	 * The ListBox containing the selected template files.
	 */
	protected List listbox;

	/**
	 * The Add Button.
	 */
	protected Button addButton;

	/**
	 * The Remove Button.
	 */
	protected Button removeButton;

	/**
	 * The RemoveAll Button.
	 */
	protected Button removeAllButton;

	/**
	 * The TextField for the path of the template file.
	 */
	protected Text templateField;

	/**
	 * Remember the loaded model file.
	 */
	protected String loadedModedFile;

	/**
	 * The displayed ResourceSet.
	 */
	protected ResourceSet resourceSet;

	/**
	 * Error message if model could not be loaded.
	 */
	protected String modelError = PluginProperties.wizards_ModelError_label;

	/**
	 * In creation mode, the page can be skipped.
	 */
	private boolean creationMode = false;
	

	/**
	 * Pass in the selection.
	 * 
	 * @param pageId
	 *            The name of the page.
	 * @param workbench
	 *            The workbench.
	 */
	public ImportTemplateWizardPage(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
		Composite composite = new Composite(parent, SWT.NONE);
		composite.setLayout(new GridLayout(10, false));
		composite.setLayoutData(WizardHelper.createData(GridData.FILL,
				GridData.FILL, true, false, -1, -1));

		// PackageTree
		Tree packageTree = WizardHelper.createPackageTree(composite);

		// PackageViewer
		if (GeneralHelper.getActiveInstance() == null)
		{
			packageViewer = WizardHelper.createPackageViewer(null, packageTree);
		}
		else 
		{
			packageViewer = WizardHelper.createPackageViewer(getAdapterFactory(),
					packageTree);
		}

		// ListBox
		listbox = WizardHelper.createListBox(composite);
		listbox.addSelectionListener(new SelectionAdapter()
		{

			@Override
			public void widgetSelected(SelectionEvent event)
			{
				removeButton.setEnabled(listbox.getSelectionIndex() != -1);
				removeAllButton.setEnabled(listbox.getSelectionIndex() != -1);

				loadedModedFile = WizardHelper.showModelInBox(listbox,
						packageViewer, resourceSet, loadedModedFile, modelError);
			}
		});

		// Add Button
		addButton = WizardHelper.createAddButton(composite);
		addButton.addSelectionListener(new SelectionAdapter()
		{

			@Override
			public void widgetSelected(SelectionEvent event)
			{
				WizardHelper.addListBox(templateField, listbox);
				selectFileField();
				setPageComplete(validatePage());
			}
		});

		// Remove Button
		removeButton = WizardHelper.createRemoveButton(composite);
		removeButton.addSelectionListener(new SelectionAdapter()
		{

			@Override
			public void widgetSelected(SelectionEvent event)
			{
				WizardHelper.removeListBoxItem(listbox);
				setPageComplete(validatePage());
			}
		});

		// RemoveAll Button
		removeAllButton = WizardHelper.createRemoveAllButton(composite);
		removeAllButton.addSelectionListener(new SelectionAdapter()
		{

			@Override
			public void widgetSelected(SelectionEvent event)
			{
				WizardHelper.removeAllListBoxItems(listbox);
				selectFileField();
				setPageComplete(validatePage());
			}
		});

		// Filename Textfield
		templateField = WizardHelper.createTemplateField(composite);
		templateField.addModifyListener(addvalidator);

		// Browse Button
		Button browseButton = WizardHelper.createBrowseButton(composite);
		browseButton.addSelectionListener(new SelectionAdapter()
		{

			@Override
			public void widgetSelected(SelectionEvent event)
			{
				String fileExtension = WEEditor.getTemplateExtension();
				String fileExtensionName = PluginProperties.wizards_Files_templatefiles;
				String filePath = TemplateHandler.saveFilePathDialog(getShell(),
						fileExtension, fileExtensionName, SWT.OPEN);
				if (filePath != null)
				{
					if (!filePath.endsWith("." + fileExtension)) //$NON-NLS-1$
					{
						filePath = filePath + "." + fileExtension; //$NON-NLS-1$
					}
					templateField.setText(filePath);
				}
			}
		});

		// Validate
		setPageComplete(validatePage());
		setControl(composite);
	}


	/* (non-Javadoc)
	 * @see org.eclipse.jface.wizard.WizardPage#getNextPage()
	 */
	@Override
	public IWizardPage getNextPage()
	{
		if (creationMode)
		{
			return super.getNextPage();
		}
		else
		{
			// in the template wizard, it should be the last page (disable next page)
			return null;
		}
	}

	
	
	/**
	 * @param creationMode The creationMode to set.
	 */
	public void setCreationMode(boolean creationMode)
	{
		this.creationMode = creationMode;
	}


	/**
	 * Validate the Page (a filename must be selected)
	 * 
	 * @return Returns if the page is valid
	 */
	public boolean validatePage()
	{
		// always return true in creation mode (creation wizard allows to skip templates)
		if (creationMode)
		{
			return true;
		}

		// disable "next" button if user has switched back to first page
		if (getContainer().getCurrentPage() != this)
		{
			return false;
		}
		
		if (listbox.getItemCount() == 0)
		{
			setMessage(PluginProperties.wizards_ImportNoSelected_error);
			return false;
		}

		setMessage(null);
		return true;
	}
	
	
	/**
	 * Listen for modifications of the filename textfield. The add button should only be
	 * enabled if text was entered.
	 */
	protected ModifyListener addvalidator = new ModifyListener()
	{

		public void modifyText(ModifyEvent e)
		{
			addButton.setEnabled(templateField.getText().length() != 0);
		}
	};


	/**
	 * Changes the visibility and sets the focus on the filename textfield
	 * 
	 * @param visible
	 *            The Visibility
	 */
	@Override
	public void setVisible(boolean visible)
	{
		super.setVisible(visible);
		if (visible)
		{
			templateField.setFocus();
		}
	}


	/**
	 * Select the filename textfield
	 */
	public void selectFileField()
	{
		templateField.selectAll();
		templateField.setFocus();
	}


	/**
	 * Returns an ArrayList of the selected templates. (Ignores models which could not be
	 * loaded correctly)
	 * 
	 * @return The selected templates
	 */
	@SuppressWarnings("unchecked")
	public ArrayList getTemplates()
	{
		ArrayList result = new ArrayList();

		for (int i = 0; i < listbox.getItems().length; i++)
		{
			if (!modelError.equals(listbox.getItems()[i]))
			{
				result.add(new String(listbox.getItems()[i]));
			}
		}

		return result;
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
	 */
	@Override
	public void dispose()
	{
		// dispose of everything
		packageViewer = null;
		listbox.dispose();
		addButton.dispose();
		removeButton.dispose();
		removeAllButton.dispose();
		templateField.dispose();
		resourceSet = null;

		super.dispose();
	}

}