/**
 * File:    NewViewWizardPage.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 java.io.File;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.jwt.we_view_editor.PluginProperties;
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.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.dialogs.ContainerSelectionDialog;


/**
 * Setting all informations of this file (project, filename etc.), only allowed extension
 * is .view
 */

public class NewViewWizardPage
		extends WizardPage
{

	/**
	 * The Textfield where the project is set, that the view should belong to.
	 */
	private Text containerText;

	/**
	 * The Textfield where the name of the view is set.
	 */
	private Text viewnameText;

	/**
	 * The Tectfield where the filename of the view-file is set.
	 */
	private Text fileText;

	/**
	 * Necessary for the constructor and initialize().
	 */
	private ISelection selection;

	/**
	 * The Grid that the textfields and browse-button belong to.
	 */
	private GridData gd;

	/**
	 * Name of the composite in the wizard the wizard-page will be added to.
	 */
	private Composite container;


	/**
	 * The constructor.
	 * 
	 * @param pageName
	 */
	public NewViewWizardPage(ISelection selection)
	{
		super("wizardPage"); //$NON-NLS-1$
		setTitle(PluginProperties.newWizard_pageTitle);
		setDescription(PluginProperties.newWizard_wizardDescription);
		this.selection = selection;
	}


	/**
	 * Inits all swt-components.
	 */
	public void createControl(Composite parent)
	{
		// container layout
		container = new Composite(parent, SWT.NULL);
		GridLayout layout = new GridLayout();
		container.setLayout(layout);
		layout.numColumns = 3;
		layout.verticalSpacing = 9;

		Label label;

		if (!(Platform.getProduct().getName() != null && Platform.getProduct().getName()
				.toLowerCase().contains("agilpro"))) //$NON-NLS-1$
		{

			// select project
			label = new Label(container, SWT.NULL);
			label.setText(PluginProperties.newWizard_project);

			containerText = new Text(container, SWT.BORDER | SWT.SINGLE);
			gd = new GridData(GridData.FILL_HORIZONTAL);
			containerText.setLayoutData(gd);
			containerText.addModifyListener(new ModifyListener()
			{

				public void modifyText(ModifyEvent e)
				{
					dialogChanged();
				}
			});

			Button button = new Button(container, SWT.PUSH);
			button.setText(PluginProperties.newWizard_browse);
			button.addSelectionListener(new SelectionAdapter()
			{

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

		// enter file name
		label = new Label(container, SWT.NULL);
		label.setText(PluginProperties.newWizard_fileName);

		fileText = new Text(container, SWT.BORDER | SWT.SINGLE);
		gd = new GridData(GridData.FILL_HORIZONTAL);

		fileText.setLayoutData(gd);
		fileText.addModifyListener(new ModifyListener()
		{

			public void modifyText(ModifyEvent e)
			{
				dialogChanged();
			}
		});

		// empty label for the third column to get a new line below
		Label placeHolder = new Label(container, SWT.NULL);
		placeHolder.setText(" "); //$NON-NLS-1$

		// enter view name
		Label labelViewname = new Label(container, SWT.NULL);
		labelViewname.setText(PluginProperties.newWizard_viewName);

		viewnameText = new Text(container, SWT.BORDER | SWT.SINGLE);
		viewnameText.setLayoutData(gd);

		viewnameText.addModifyListener(new ModifyListener()
		{

			public void modifyText(ModifyEvent e)
			{
				dialogChanged();
			}
		});

		initialize();
		dialogChanged();
		setControl(container);
	}


	/**
	 * Inits the page for the wizard and sets the default file-name for the view.
	 */
	private void initialize()
	{

		if (selection != null && selection.isEmpty() == false
				&& selection instanceof IStructuredSelection && containerText != null)
		{
			IStructuredSelection ssel = (IStructuredSelection) selection;

			if (ssel.size() > 1)
			{
				return;
			}

			Object obj = ssel.getFirstElement();

			if (obj instanceof IResource)
			{
				IContainer container;

				if (obj instanceof IContainer)
				{
					container = (IContainer) obj;
				}
				else
				{
					container = ((IResource) obj).getParent();
				}

				containerText.setText(container.getFullPath().toString());
			}
		}
		fileText.setText(PluginProperties.newWizard_newFile_fileName
				+ "." + PluginProperties.plugin_view_extension); //$NON-NLS-1$	
	}


	/**
	 * Browse to a project.
	 */
	private void handleBrowse()
	{
		ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(),
				ResourcesPlugin.getWorkspace().getRoot(), false,
				PluginProperties.newWizard_selectProject);

		if (dialog.open() == ContainerSelectionDialog.OK)
		{
			Object[] result = dialog.getResult();

			if (result.length == 1)
			{
				containerText.setText(((Path) result[0]).toString());
			}
		}
	}


	/**
	 * Checks, if necessary informations like filename are set.
	 */
	private void dialogChanged()
	{
		IResource container = ResourcesPlugin.getWorkspace().getRoot().findMember(
				new Path(getContainerName()));
		String fileName = getFileName();

		if (getContainerName().length() == 0 && containerText != null)
		{
			updateStatus(PluginProperties.newWizard_error_unspecifiedProject);
			return;
		}

		if (container == null
				|| (container.getType() & (IResource.PROJECT | IResource.FOLDER)) == 0
				&& containerText != null)
		{
			updateStatus(PluginProperties.newWizard_error_notExistingProject);
			return;
		}

		if (!container.isAccessible() && containerText != null)
		{
			updateStatus(PluginProperties.newWizard_error_notWritableProject);
			return;
		}

		File tempFile = new File(container.getLocation() + "\\" + getFileName()); //$NON-NLS-1$

		if (tempFile.exists())
		{
			updateStatus(getFileName()
					+ " " + PluginProperties.newWizard_error_existingFile); //$NON-NLS-1$
			return;
		}

		if (fileName.length() == 0)
		{
			updateStatus(PluginProperties.newWizard_error_unspecifiedFileName);
			return;
		}

		if (fileName.replace('\\', '/').indexOf('/', 1) > 0  && containerText != null)
		{
			updateStatus(PluginProperties.newWizard_error_notValidFileName);
			return;
		}

		int dotLoc = fileName.lastIndexOf('.');

		if (dotLoc != -1)
		{
			String ext = fileName.substring(dotLoc + 1);

			if (ext.equalsIgnoreCase("view") == false) //$NON-NLS-1$
			{
				updateStatus(PluginProperties.newWizard_error_wrongFileExtension
						+ "\"view\""); //$NON-NLS-1$
				return;
			}
		}

		// no view name set
		if (getViewnameText().length() == 0)
		{
			updateStatus(PluginProperties.newWizard_error_noViewNameSet);
			return;
		}

		updateStatus(null);
	}


	/**
	 * Updates the status-messages, f.e caused by incorrect settings.
	 * 
	 * @param message
	 */
	private void updateStatus(String message)
	{
		setErrorMessage(message);
		setPageComplete(message == null);
	}


	/**
	 * Returns the project-name by getting the text of the textfield.
	 * 
	 * @return
	 */
	public String getContainerName()
	{
		if (containerText != null)
		{
			return containerText.getText();
		}
		else
		{
			return "";
		}
	}


	/**
	 * Returns the file-name by getting the text of the textfield.
	 * 
	 * @return
	 */
	public String getFileName()
	{
		return fileText.getText();
	}


	/**
	 * Returns the view-name by getting the text of the textfield.
	 * 
	 * @return
	 */
	public String getViewnameText()
	{
		return viewnameText.getText();
	}
}