//------------------------------------------------------------------------------
// 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.msp.ui.wizards;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.eclipse.epf.export.msp.ExportMSPPlugin;
import org.eclipse.epf.export.msp.ExportMSPResources;
import org.eclipse.epf.export.msp.ExportMSPService;
import org.eclipse.epf.export.msp.ExportMSPServiceException;
import org.eclipse.epf.export.msp.ExportOptions;
import org.eclipse.epf.export.msp.IExportMSPService;
import org.eclipse.epf.export.msp.ui.internal.ExportMSPWizardExtensionManager;
import org.eclipse.epf.export.msp.ui.preferences.ExportMSPPreferences;
import org.eclipse.epf.library.ui.preferences.LibraryUIPreferences;
import org.eclipse.epf.publishing.services.PublishOptions;
import org.eclipse.epf.publishing.ui.preferences.PublishingUIPreferences;
import org.eclipse.epf.uma.DeliveryProcess;
import org.eclipse.epf.uma.Process;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IExportWizard;
import org.eclipse.ui.IWorkbench;

/**
 * The Export Microsoft Project wizard.
 * <p>
 * This wizard exports a capability pattern or delivery process to a Microsoft
 * Project. The current implementation generates a XML file that adheres to the
 * Microsoft Project 2003 XML Schema.
 * 
 * @author Kelvin Low
 * @since 1.0
 */
public class ExportMSPWizard extends Wizard implements IExportWizard {

	// The workbench instance.
	protected IWorkbench workbench;

	// The workbench selection when the wizard was started.
	protected IStructuredSelection selection;

	// The wizard page that prompts the user to select a process and export
	// options.
	protected SelectProcessPage selectProcessPage;

	// The wizard page that prompts the user to specify the publishing options.
	protected SelectPublishOptionsPage selectPublishOptionsPage;

	// The wizard page that prompts the user to specify the export directory.
	protected SelectExportDirectoryPage selectExportDirPage;

	// The export options.
	protected ExportOptions exportOptions = new ExportOptions();

	// The publishing options.
	protected PublishOptions publishingOptions = new PublishOptions();

	// An extender of this wizard.
	protected IExportMSPWizardExtender wizardExtender;

	/**
	 * Creates a new instance.
	 */
	public ExportMSPWizard() {
		setWindowTitle(ExportMSPResources.exportMSPWizard_title);
	}

	/**
	 * @see org.eclipse.ui.IWorkbenchWizard#init(IWorkbench,
	 *      IStructuredSelection)
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.workbench = workbench;
		this.selection = selection;
		this.wizardExtender = ExportMSPWizardExtensionManager.getInstance()
				.getWizardExtender();
	}

	/**
	 * @see org.eclipse.jface.wizard.Wizard#addPages()
	 */
	public void addPages() {
		selectProcessPage = new SelectProcessPage(exportOptions);
		selectPublishOptionsPage = new SelectPublishOptionsPage(false,
				publishingOptions);
		selectExportDirPage = new SelectExportDirectoryPage();

		super.addPage(selectProcessPage);
		super.addPage(selectPublishOptionsPage);
		super.addPage(selectExportDirPage);

		if (wizardExtender != null) {
			List pages = wizardExtender.getPageContributions();
			for (int i = 0; i < pages.size(); i++) {
				IWizardPage page = (IWizardPage) pages.get(i);
				super.addPage(page);
			}
		}
	}

	/**
	 * @see org.eclipse.jface.wizard.Wizard#createPageControls(Composite)
	 */
	public void createPageControls(Composite pageContainer) {
		super.createPageControls(pageContainer);
		pageContainer.getShell().setImage(
				ExportMSPPlugin.getDefault().getSharedImage(
						"full/obj16/MSProject.gif")); //$NON-NLS-1$
	}

	/**
	 * @see org.eclipse.jface.wizard.IWizard#canFinish()
	 */
	public boolean canFinish() {
		if (wizardExtender != null && !wizardExtender.canFinish()) {
			return false;
		}
		return getContainer().getCurrentPage() == selectExportDirPage
				&& selectExportDirPage.isPageComplete();
	}

	/**
	 * @see org.eclipse.jface.wizard.IWizard#performFinish()
	 */
	public boolean performFinish() {
		Process process = selectProcessPage.getProcess();
		String processContextName = selectProcessPage.getProcessContextName();
		boolean publishConfiguration = selectProcessPage
				.getPublishedConfiguration();
		if (publishConfiguration) {
			publishingOptions = selectPublishOptionsPage.getPublishingOptions();
			PublishingUIPreferences.setTitle(publishingOptions.getTitle());
			PublishingUIPreferences.setBannerImage(publishingOptions
					.getBannerImage());
			PublishingUIPreferences.setAboutHTML(publishingOptions
					.getAboutHTML());
			PublishingUIPreferences.setFeedbackURL(publishingOptions
					.getFeedbackURL());
			PublishingUIPreferences.setIncludeGlossary(publishingOptions
					.isGenerateGlossary());
			PublishingUIPreferences.setIncludeIndex(publishingOptions
					.isGenerateIndex());
			PublishingUIPreferences.setCheckExternalLinks(publishingOptions
					.isCheckExtLinks());
			LibraryUIPreferences.setPublishUnopenActivitydd(publishingOptions
					.isAutoGenerateActivityDiagrams());
			LibraryUIPreferences
					.setPublishADForActivityExtension(publishingOptions
							.isUnopenExtendedActivityDiagram());
		} else {
			publishingOptions = null;
		}

		String templateName = selectExportDirPage.getTemplateName();
		String targetDir = selectExportDirPage.getTargetDirectory();

		String templateFileName = templateName + ".xml"; //$NON-NLS-1$
		File templateFile = new File(targetDir, templateFileName);
		if (templateFile.exists()) {
			boolean ok = ExportMSPPlugin.getDefault().getMsgDialog()
					.displayPrompt(
							ExportMSPResources.exportMSPWizard_title,
							NLS
									.bind(ExportMSPResources.overwriteText_msg,
											(new String[] { templateFileName,
													targetDir })));
			if (!ok) {
				return false;
			}
		}

		try {
			ExportOptions exportOptions = new ExportOptions();
			exportOptions.put(ExportOptions.PUBLISH_CONFIG, new Boolean(
					publishingOptions != null));
			exportOptions.put(ExportOptions.EXPORT_ONLY_PLANNED_ELEMENTS,
					new Boolean(selectProcessPage
							.getExportOnlyPlannedElements()));

			if (wizardExtender != null) {
				Map options = wizardExtender.getExportOptions();
				if (options != null) {
					for (Iterator it = options.keySet().iterator(); it
							.hasNext();) {
						String name = (String) it.next();
						Object value = options.get(name);
						exportOptions.put(name, value);
					}
				}
			}

			IExportMSPService service = null;
			if (wizardExtender != null) {
				service = wizardExtender.getExportMSPService();
			}
			if (service == null) {
				service = ExportMSPService.getInstance();
			}

			boolean success = service.exportMSPXML(process, templateName,
					new File(targetDir), exportOptions, publishingOptions);

			if (success) {
				ExportMSPPlugin.getDefault().getMsgDialog().displayInfo(
						ExportMSPResources.exportMSPWizard_title,
						NLS.bind(ExportMSPResources.completedText_msg,
								(new String[] { process.getName(),
										templateFile.getAbsolutePath() })));
			}
		} catch (ExportMSPServiceException e) {
			ExportMSPPlugin.getDefault().getMsgDialog().displayError(
					ExportMSPResources.exportMSPWizard_title,
					NLS.bind(ExportMSPResources.exportMSPError_msg,
							(new String[] { process.getName(),
									templateFile.getAbsolutePath() })),
					ExportMSPResources.exportMSPError_reason, e);
		}

		ExportMSPPlugin plugin = ExportMSPPlugin.getDefault();
		IPreferenceStore prefStore = plugin.getPreferenceStore();
		if (process != null) {
			if (process instanceof DeliveryProcess) {
				prefStore.setValue(ExportMSPPreferences.PROCESS_TYPE,
						"DeliveryProcess"); //$NON-NLS-1$
			} else {
				prefStore.setValue(ExportMSPPreferences.PROCESS_TYPE,
						"CapabilityPattern"); //$NON-NLS-1$
			}
			prefStore.setValue(ExportMSPPreferences.PROCESS_NAME, process
					.getName());
		}
		prefStore.setValue(ExportMSPPreferences.PROCESS_CONTEXT,
				processContextName);
		prefStore.setValue(ExportMSPPreferences.TEMPLATE_NAMES, templateName);
		prefStore.setValue(ExportMSPPreferences.TARGET_DIRECTORIES, targetDir);
		plugin.savePluginPreferences();

		return true;
	}

	/**
	 * Returns the wizard extender.
	 */
	public IExportMSPWizardExtender getWizardExtender() {
		return wizardExtender;
	}

	/**
	 * Returns the wizard page that prompts the user to select a process and
	 * export options.
	 */
	public SelectProcessPage getSelectProcessPage() {
		return selectProcessPage;
	}

	/**
	 * Returns the wizard page that prompts the user to specify the publishing
	 * options.
	 */
	public SelectPublishOptionsPage selectPublishOptionsPage() {
		return selectPublishOptionsPage;
	}

	/**
	 * Returns the wizard page that prompts the user to specify the export
	 * directory.
	 */
	public SelectExportDirectoryPage getSelectExportDirectoryPage() {
		return selectExportDirPage;
	}

	/**
	 * Returns the export options.
	 */
	public ExportOptions getExportOptions() {
		return exportOptions;
	}

}
