//------------------------------------------------------------------------------
// Copyright (c) 2005, 2006 IBM Corporation and others.
// 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:
// IBM Corporation - initial implementation
//------------------------------------------------------------------------------
package org.eclipse.epf.export.wizards;

import java.io.File;

import org.eclipse.epf.authoring.ui.preferences.LibraryLocationData;
import org.eclipse.epf.common.utils.FileUtil;
import org.eclipse.epf.common.utils.StrUtil;
import org.eclipse.epf.export.ExportResources;
import org.eclipse.epf.library.ui.wizards.BaseWizardPage;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.swt.SWT;
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.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;


/**
 * A wizard page that prompts the user to select a destination directory for an
 * export or import operation.
 * 
 * @author Bingxue Xu
 * @author Kelvin Low
 * @since 1.0
 */
public class DestinationCommonPage extends BaseWizardPage implements Listener {

	private static final String pageTitle = ExportResources.DestinationCommonPage_title; //$NON-NLS-1$

	private static final String pageDesc = ExportResources.DestinationCommonPage_desc; //$NON-NLS-1$

	private static final String nameLabel = ExportResources.DestinationCommonPage_label_name; //$NON-NLS-1$

	protected Composite container;

	protected Text ctrl_name;

	protected Text ctrl_exportPath;

	protected Button ctrl_browse_button;

	protected Button ctrl_default_checkbox;

	private Text ctrlInEditing;

	private String parentDir;

	protected LibraryLocationData llData;

	/**
	 * Creates a new instance.
	 */
	public DestinationCommonPage(String pageName, LibraryLocationData llData) {
		super(pageName);
		setTitle(pageTitle);
		setDescription(pageDesc);
		this.llData = llData;
	}

	protected Label createLabel(Composite parent, String text, int nCol) {
		Label label = new Label(parent, SWT.NONE);
		label.setText(text);
		GridData gridData = new GridData(GridData.BEGINNING);
		gridData.horizontalSpan = nCol;
		label.setLayoutData(gridData);
		return label;
	}

	public void createControl(Composite parent) {
		container = new Composite(parent, SWT.NONE);
		container.setLayout(new GridLayout(3, false));

		createLabel(container, nameLabel);
		ctrl_name = createEditableText(container, "", 360, 1); //$NON-NLS-1$
		createLabel(container, ""); //$NON-NLS-1$

		createLabel(container, ExportResources.DestinationCommonPage_label_dir); //$NON-NLS-1$
		ctrl_exportPath = createEditableText(container, "", 420, 1); //$NON-NLS-1$
		ctrl_browse_button = new Button(container, SWT.NONE);
		ctrl_browse_button.setText(ExportResources.DestinationCommonPage_label_browse); //$NON-NLS-1$
		ctrl_browse_button.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				openDirectoryDialog();
			}
		});

		createLabel(container, ""); //$NON-NLS-1$		
		ctrl_default_checkbox = new Button(container, SWT.CHECK);
		ctrl_default_checkbox.setText(ExportResources.DestinationCommonPage_label_default_dir); //$NON-NLS-1$

		ctrl_default_checkbox.setSelection(true);
		ctrl_exportPath.setText(getDefaultExportPath());
		ctrl_exportPath.setEditable(false);
		ctrl_browse_button.setEnabled(false);

		addListeners();

		setControl(container);
		setPageComplete(false);
	}

	private void addListeners() {
		ctrl_name.addListener(SWT.Modify, this);
		ctrl_name.addListener(SWT.FocusIn, this);
		ctrl_name.addListener(SWT.FocusOut, this);
		ctrl_exportPath.addListener(SWT.FocusIn, this);
		ctrl_exportPath.addListener(SWT.Modify, this);
		ctrl_exportPath.addListener(SWT.FocusOut, this);
		ctrl_default_checkbox.addListener(SWT.Selection, this);
	}

	public void setVisible(boolean visible) {
		super.setVisible(visible);
		if (visible) {
			Display display = container.getDisplay();
			if (!(display == null || display.isDisposed())) {
				display.asyncExec(new Runnable() {
					public void run() {
						ctrl_name.setFocus();
					}
				});
			}
		}
	}

	public void handleEvent(Event event) {
		Wizard wizard = (Wizard) getWizard();

		// Remember the parent dir minus the library name.
		if (event.widget == ctrl_name && event.type == SWT.FocusIn) {
			parentDir = ctrl_exportPath.getText();
			String currentName = StrUtil.makeValidFileName(ctrl_name.getText()
					.trim());

			if (!currentName.equals(ctrl_name.getText())) {
				ctrl_name.setText(currentName);
			}

			if (currentName.length() > 0
					&& parentDir.endsWith(File.separator + currentName)) {
				int idx = parentDir.lastIndexOf(File.separator + currentName);
				parentDir = parentDir.substring(0, idx);
			}
			if (!parentDir.endsWith(File.separator))
				parentDir += File.separator;

			ctrlInEditing = ctrl_name;
		}

		// Whenever name changes, update the library path accordingly.
		if (event.widget == ctrl_name && ctrlInEditing == ctrl_name) {
			ctrl_exportPath.setText(parentDir
					+ StrUtil.makeValidFileName(ctrl_name.getText()));

		}

		if (event.widget == ctrl_name && event.type == SWT.FocusOut) {
			ctrlInEditing = null;
		}

		if (event.widget == ctrl_exportPath && event.type == SWT.FocusIn) {
			ctrlInEditing = ctrl_exportPath;
		}

		if (event.widget == ctrl_exportPath && ctrlInEditing == ctrl_exportPath) {
			String parentLibPath = ctrl_exportPath.getText();
			int idx = parentLibPath.lastIndexOf(File.separator);
			String libName = parentLibPath.substring(idx + 1);
			ctrl_name.setText(libName);
		}

		if (event.widget == ctrl_exportPath && event.type == SWT.FocusOut) {
			ctrlInEditing = null;
		}

		if (event.widget == ctrl_default_checkbox) {
			if (!ctrl_default_checkbox.getSelection()) {
				ctrl_name.setText(""); //$NON-NLS-1$
				ctrl_exportPath.setText(getDefaultExportPath());
				ctrl_exportPath.setEditable(true);
				ctrl_browse_button.setEnabled(true);
				ctrl_name.setEditable(true);
				ctrl_name.setEnabled(true);
			} else {
				ctrl_name.setText(""); //$NON-NLS-1$
				ctrl_exportPath.setText(getDefaultExportPath());
				ctrl_exportPath.setEditable(false);
				ctrl_browse_button.setEnabled(false);
				ctrl_name.setEditable(true);
				ctrl_name.setEnabled(true);
			}
			appendNemeToPath();
		}
		setPageComplete(isPageComplete());
		wizard.getContainer().updateButtons();

	}

	private String getDefaultExportPath() {
		String defExportPPath = System.getProperty("user.home") + //$NON-NLS-1$
				FileUtil.FILE_SEP + "EPF" + //$NON-NLS-1$
				FileUtil.FILE_SEP + "Export"; //$NON-NLS-1$
		return defExportPPath;
	}

	private void appendNemeToPath() {
		String libName = ctrl_name.getText().trim();
		String libPath = ctrl_exportPath.getText().trim();
		if (libName.length() > 0) {
			if (!libPath.endsWith(File.separator))
				libPath += File.separator;
			ctrl_exportPath.setText(libPath + libName);
		}

	}

	protected void saveToDataModel() {
		llData.setLibName(ctrl_name.getText());
		llData.setParentFolder(ctrl_exportPath.getText());
	}

	private void openDirectoryDialog() {
		try {
			DirectoryDialog dd = new DirectoryDialog(container.getShell(),
					SWT.NONE);
			dd.setFilterPath(ctrl_exportPath.getText());

			String destination = dd.open();
			if (destination != null) {
				ctrl_exportPath.setText(destination);
				File destinationFile = new File(destination);
				ctrl_name.setText(destinationFile.getName());
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
