/**
 * File:    CreationWizardPageFileName.java
 * Created: 13.03.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.conf.presentation;

import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.eclipse.core.runtime.Path;
import org.eclipse.emf.common.util.URI;
import org.eclipse.jface.wizard.WizardPage;
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.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;


/**
 * This is the page where the filename of the new model can be entered along with the name
 * of the standard {@link Package} and {@link Activity} which are created automatically.
 * 
 * @version $Id: CreationWizardTemplatePageHelper.java
 * @author Christian Saad (csaad@gmx.net), Programming distributed Systems Lab, University
 *         of Augsburg, Germany, www.ds-lab.org
 */
public class CreationWizardPageFileName
		extends WizardPage
{


	/**
	 * The textfield for the file name.
	 */
	protected Text fileField;


	/**
	 * The supported extensions for created files. <!-- begin-user-doc --> <!--
	 * end-user-doc -->
	 * 
	 * @generated
	 */
	public static final List<String> FILE_EXTENSIONS = Collections
			.unmodifiableList(Arrays.asList(ConfMetaModelEditorPlugin.INSTANCE.getString(
					"_UI_ConfEditorFilenameExtensions").split("\\s*,\\s*")));

	/**
	 * A formatted list of supported file extensions, suitable for display. <!--
	 * begin-user-doc --> <!-- end-user-doc -->
	 * 
	 * @generated
	 */
	public static final String FORMATTED_FILE_EXTENSIONS = ConfMetaModelEditorPlugin.INSTANCE
			.getString("_UI_ConfEditorFilenameExtensions").replaceAll("\\s*,\\s*", ", ");

	
	/**
	 * Pass in the selection.
	 * 
	 * @param pageId
	 *            The name of the page.
	 */
	public CreationWizardPageFileName(String pageId)
	{
		super(pageId);
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
	 */
	public void createControl(Composite parent)
	{
		Composite composite = new Composite(parent, SWT.NONE);
		{
			GridLayout layout = new GridLayout();
			layout.numColumns = 1;
			layout.verticalSpacing = 12;
			composite.setLayout(layout);

			GridData data = new GridData();
			data.verticalAlignment = GridData.FILL;
			data.grabExcessVerticalSpace = true;
			data.horizontalAlignment = GridData.FILL;
			composite.setLayoutData(data);
		}


		// file
		Label resourceURILabel = new Label(composite, SWT.LEFT);
		{
			resourceURILabel.setText("File"); //nls

			GridData data = new GridData();
			data.horizontalAlignment = GridData.FILL;
			resourceURILabel.setLayoutData(data);
		}

		Composite fileComposite = new Composite(composite, SWT.NONE);
		{
			GridData data = new GridData();
			data.horizontalAlignment = GridData.FILL;
			data.grabExcessHorizontalSpace = true;
			fileComposite.setLayoutData(data);

			GridLayout layout = new GridLayout();
			data.horizontalAlignment = GridData.FILL;
			layout.marginHeight = 0;
			layout.marginWidth = 0;
			layout.numColumns = 2;
			fileComposite.setLayout(layout);
		}

		fileField = new Text(fileComposite, SWT.BORDER);
		{
			GridData data = new GridData();
			data.horizontalAlignment = GridData.FILL;
			data.grabExcessHorizontalSpace = true;
			data.horizontalSpan = 1;
			fileField.setLayoutData(data);
		}

		fileField.addModifyListener(validator);

		Button resourceURIBrowseFileSystemButton = new Button(fileComposite, SWT.PUSH);
		resourceURIBrowseFileSystemButton.setText("Browse"); //NLS

		resourceURIBrowseFileSystemButton.addSelectionListener(new SelectionAdapter()
		{

			@Override
			public void widgetSelected(SelectionEvent event)
			{
				String fileExtension = ConfMetaModelEditorPlugin.INSTANCE.getString("_UI_ConfEditorFilenameExtensions"); //$NON-NLS-1$
				String filePath = openFilePathDialog(getShell(), null,
						SWT.OPEN);
				if (filePath != null)
				{
					if (!filePath.endsWith("." + fileExtension)) //$NON-NLS-1$
					{
						filePath = filePath + "." + fileExtension; //$NON-NLS-1$
					}
					fileField.setText(filePath);
				}
			}
		});

		// finish creation
		setPageComplete(validatePage());
		setControl(composite);
	}

	
	/**
	 * Opens a file dialog.
	 * 
	 * @param shell
	 *            A shell which will be the parent of the new instance.
	 * @param fileExtensionFilter
	 *            The file extensions which the dialog will use to filter the files it
	 *            shows to the argument, which may be <code>null</code>.
	 * @param style
	 *            The style of dialog to construct.
	 * @return The path the user selected.
	 */
	private static String openFilePathDialog(Shell shell, String fileExtensionFilter,
			int style)
	{
		FileDialog fileDialog = new FileDialog(shell, style);
		if (fileExtensionFilter == null)
		{
			fileExtensionFilter = "*." + ConfMetaModelEditorPlugin.INSTANCE.getString("_UI_ConfEditorFilenameExtensions"); //$NON-NLS-1$ //$NON-NLS-2$
		}
		fileDialog.setFilterExtensions(new String[]
		{ fileExtensionFilter });
		fileDialog.setFilterNames(new String[]
		{ ConfMetaModelEditorPlugin.INSTANCE.getString("_UI_ConfEditorFilenameExtensions") }); //$NON-NLS-1$

		fileDialog.open();
		if (fileDialog.getFileName() != null && fileDialog.getFileName().length() > 0)
		{
			return fileDialog.getFilterPath() + File.separator + fileDialog.getFileName();
		}
		return null;
	}

	
	/**
	 * Checks if filename was entered
	 */
	protected ModifyListener validator = new ModifyListener()
	{

		public void modifyText(ModifyEvent e)
		{
			setPageComplete(validatePage());
		}
	};


	/**
	 * Validates the page (file name must be entered).
	 */
	protected boolean validatePage()
	{
		URI fileURI = getFileURI();
		setErrorMessage(null);

		if ((fileURI == null || fileURI.isEmpty()))
		{
			return false;
		}

		String extension = new Path(getFileURI().toFileString()).getFileExtension();
		if (extension == null || !FILE_EXTENSIONS.contains(extension))
		{
			String key = FILE_EXTENSIONS.size() > 1 ? "_WARN_FilenameExtensions" : "_WARN_FilenameExtension"; //$NON-NLS-1$ //$NON-NLS-2$
			setErrorMessage(ConfMetaModelEditorPlugin.INSTANCE.getString(key,
					new Object[]
					{ FORMATTED_FILE_EXTENSIONS }));
			return false;
		}
		
		return true;
	}


	/**
	 * @return The entered URI.
	 */
	public URI getFileURI()
	{
		try
		{
			return URI.createFileURI(fileField.getText());
		}
		catch (Exception exception)
		{
		}
		return null;
	}
	
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.jface.dialogs.DialogPage#setVisible(boolean)
	 */
	@Override
	public void setVisible(boolean visible)
	{
		super.setVisible(visible);
		if (visible && fileField.getVisible())
		{
			fileField.setFocus();
		}
	}


	/**
	 * @return The entered URI.
	 */
	public File getModelFile()
	{
		try
		{
			return new File(URI.createFileURI(fileField.getText()).toFileString());
		}
		catch (Exception exception)
		{
		}
		return null;
	}


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

}