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

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

import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.epf.common.utils.FileUtil;
import org.eclipse.epf.library.LibraryService;
import org.eclipse.epf.library.LibraryServiceUtil;
import org.eclipse.epf.library.configuration.ConfigurationHelper;
import org.eclipse.epf.library.ui.preferences.LibraryUIPreferences;
import org.eclipse.epf.publishing.services.PublishOptions;
import org.eclipse.epf.publishing.ui.PublishingUIPlugin;
import org.eclipse.epf.publishing.ui.PublishingUIResources;
import org.eclipse.epf.publishing.ui.preferences.PublishingUIPreferences;
import org.eclipse.epf.uma.MethodConfiguration;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWizard;

/**
 * The Publish Method Configuration wizard.
 * 
 * @author Kelvin Low
 * @author Bingxue Xu
 * @author Jinhua Xi
 * @since 1.0
 */
public class PublishConfigurationWizard extends AbstractPublishWizard {

	// The wizard pages.
	protected PublishConfigSelectConfigPage selectConfigPage;

	protected PublishConfigPublishOptionsPage publishOptionsPage;

	private Map configProcesspageMap = new HashMap();

	/**
	 * Creates a new instance.
	 */
	public PublishConfigurationWizard() {
		super();
		setWindowTitle(PublishingUIResources.publishConfigWizard_title); //$NON-NLS-1$
	}

	/**
	 * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection) {
	}

	public ImageDescriptor getImageDescriptor() {
		return 	PublishingUIPlugin.getDefault()
		.getImageDescriptor("wizban/PublishConfiguration.gif"); //$NON-NLS-1$

	}
	
	public PublishOptions getPublishOptions() {
		if ( super.dataModel == null ) {
			super.dataModel = new PublishOptions();
		}
		
		return super.dataModel;
	}
	
	/**
	 * @see org.eclipse.jface.wizard.addPages()
	 */
	public void addPages() {
		ImageDescriptor imageDescriptor = getImageDescriptor();

		selectConfigPage = new PublishConfigSelectConfigPage(
				"PublishConfigSelectOverviewPage", dataModel); //$NON-NLS-1$
		selectConfigPage.setImageDescriptor(imageDescriptor);
		addPage(selectConfigPage);

		publishOptionsPage = new PublishConfigPublishOptionsPage(
				"PublishConfigPublishOptionsPage", dataModel); //$NON-NLS-1$
		publishOptionsPage.setImageDescriptor(imageDescriptor);
		addPage(publishOptionsPage);
	}

	public IWizardPage getSelProcessPage(String configName) {

		PublishConfigSelectProcessPage selectProcessPage = (PublishConfigSelectProcessPage) configProcesspageMap
				.get(configName);

		if (selectProcessPage == null) {
			ImageDescriptor imageDescriptor = PublishingUIPlugin.getDefault()
					.getImageDescriptor("wizban/PublishConfiguration.gif"); //$NON-NLS-1$

			selectProcessPage = new PublishConfigSelectProcessPage(
					"PublishConfigSelectProcessPage", dataModel); //$NON-NLS-1$
			selectConfigPage.setImageDescriptor(imageDescriptor);
			addPage(selectProcessPage);

			configProcesspageMap.put(configName, selectProcessPage);
		}

		return selectProcessPage;
	}

	public IWizardPage getNextPage(IWizardPage page) {
		if (page == selectConfigPage) {
			if (dataModel.getSelectedConfig() != null) {
				String configName = dataModel.getSelectedConfig();
				MethodConfiguration config = LibraryServiceUtil
						.getMethodConfiguration(LibraryService.getInstance()
								.getCurrentMethodLibrary(), configName);
				List procs = ConfigurationHelper.getAllProcesses(config);
				if (procs != null && procs.size() > 0) {
					return getSelProcessPage(configName);
				} else {
					return publishOptionsPage;
				}
			} else
				return null;
		} else if (page == publishOptionsPage) {
			return null;
		} else {
			return publishOptionsPage;
		}
	}

	/**
	 * @see org.eclipse.jface.wizard.IWizard#canFinish()
	 */
	public boolean canFinish() {
		return (this.getContainer().getCurrentPage() == publishOptionsPage && publishOptionsPage
				.isPageComplete());
	}

	/**
	 * @see org.eclipse.jface.wizard.IWizard#performFinish()
	 */
	public boolean performFinish() {
		dataModel = publishOptionsPage.getPublishingOptions();
		boolean answer = checkAndCreateDir(dataModel.publicationPath);
		if (answer) {
			dataModel.setFinishPressed(true);
			PublishingUIPreferences.setPublishPath(dataModel
					.getPublicationPath());
			PublishingUIPreferences.setTitle(dataModel.getTitle());
			PublishingUIPreferences.setBannerImage(dataModel.getBannerImage());
			PublishingUIPreferences.setAboutHTML(dataModel.getAboutHTML());
			PublishingUIPreferences.setFeedbackURL(dataModel.getFeedbackURL());
			PublishingUIPreferences.setIncludeGlossary(dataModel
					.isGenerateGlossary());
			PublishingUIPreferences
					.setIncludeIndex(dataModel.isGenerateIndex());
//			PublishingUIPreferences.setIncludeSearch(dataModel
//					.isGenerateSearchDB());
//			PublishingUIPreferences.setIncludeProcessCustomization(dataModel
//					.isUseApplet());
			PublishingUIPreferences.setCheckExternalLinks(dataModel
					.isCheckExtLinks());
			LibraryUIPreferences.setPublishUnopenActivitydd(dataModel
					.isAutoGenerateActivityDiagrams());
			LibraryUIPreferences.setPublishADForActivityExtension(dataModel
					.isUnopenExtendedActivityDiagram());
			return true;
		}
		dataModel.setFinishPressed(false);
		return false;
	}

	/**
	 * @see org.eclipse.jface.wizard.IWizard#performCancel()
	 */
	public boolean performCancel() {
		dataModel.setFinishPressed(false);
		return true;
	}

	/**
	 * Checks and creates the destination path.
	 */
	protected boolean checkAndCreateDir(String dir) {
		String defaultPublishPath = PublishingUIPreferences
				.getDefaultPublishPath();
		boolean answer = false;

		IPath ecPath = Path.fromOSString(dir);
		if (!ecPath.isAbsolute()) {
			String path = defaultPublishPath
					+ System.getProperty("file.separator") + dir; //$NON-NLS-1$
			answer = PublishingUIPlugin
					.getDefault()
					.getMsgDialog()
					.displayPrompt(
							PublishingUIResources.publishConfigDialog_title, //$NON-NLS-1$
							PublishingUIResources.bind(PublishingUIResources.confirmPathDialog_text, path)); //$NON-NLS-1$

			if (answer) {
				dataModel.setPublicationPath(dir);
			} else {
				return false;
			}
		}

		File file = new File(dir);

		if (file.exists()) {
			File[] files = file.listFiles();
			if (files != null && files.length > 0) {
				answer = PublishingUIPlugin
						.getDefault()
						.getMsgDialog()
						.displayConfirmation(
								PublishingUIResources.publishConfigDialog_title, //$NON-NLS-1$
								PublishingUIResources.bind(PublishingUIResources.overwriteDialog_text, dir)); //$NON-NLS-1$

				if (answer == true) {
					try {
						answer = FileUtil
								.deleteAllFiles(file.getAbsolutePath());
						if (answer == false) {
							PublishingUIPlugin
									.getDefault()
									.getMsgDialog()
									.displayError(
											PublishingUIResources.publishConfigDialog_title, //$NON-NLS-1$
											PublishingUIResources.cannotPublishError_msg, //$NON-NLS-1$							
											PublishingUIResources.bind(PublishingUIResources.deleteFilesError_reason, dir)); //$NON-NLS-1$
							return false;

						}
					} catch (Exception e) {
						PublishingUIPlugin
								.getDefault()
								.getMsgDialog()
								.displayError(
										PublishingUIResources.publishConfigDialog_title, //$NON-NLS-1$
										PublishingUIResources.cannotPublishError_msg, //$NON-NLS-1$							
										PublishingUIResources.bind(PublishingUIResources.deleteFilesError_reason, dir), e); //$NON-NLS-1$
						return false;
					}
				}
			} else {
				return true;
			}
		} else {
			try {
				answer = file.mkdirs();
			} catch (Exception e) {
				PublishingUIPlugin
						.getDefault()
						.getMsgDialog()
						.displayError(
								PublishingUIResources.publishConfigDialog_title, //$NON-NLS-1$
								PublishingUIResources.cannotPublishError_msg, //$NON-NLS-1$
								PublishingUIResources.bind(PublishingUIResources.createDirError_reason, file.getAbsolutePath()), e); //$NON-NLS-1$
				return false;
			}
			if (!answer) {
				PublishingUIPlugin
						.getDefault()
						.getMsgDialog()
						.displayError(
								PublishingUIResources.publishConfigDialog_title, //$NON-NLS-1$
								PublishingUIResources.cannotPublishError_msg, //$NON-NLS-1$
								PublishingUIResources.bind(PublishingUIResources.createDirError_reason, file.getAbsolutePath())); //$NON-NLS-1$
				return false;
			}
		}

		return answer;
	}

}