/*
 * (c) Copyright Sysdeo SA 2001, 2002.
 * All Rights Reserved.
 */

package com.sysdeo.eclipse.tomcat;

import static com.sysdeo.eclipse.tomcat.TomcatPluginResources.NATURE_ID;
import static com.sysdeo.eclipse.tomcat.TomcatPluginResources.WIZARD_PROJECT_REMOVE_DESCRIPTION;
import static com.sysdeo.eclipse.tomcat.TomcatPluginResources.WIZARD_PROJECT_REMOVE_TITLE;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;

/**
 * TomcatProjectChangeListener
 *
 */
public class TomcatProjectChangeListener implements IResourceChangeListener {

	/**
	 * @see IResourceChangeListener#resourceChanged(IResourceChangeEvent)
	 */
	@Override
	public void resourceChanged(final IResourceChangeEvent event) {
		if (event.getResource() instanceof IProject) {
			final ITomcatProject project = create((IProject)event.getResource());
			if (project != null) {
				Display.getDefault().syncExec(new Runnable() {
						@Override
						public void run() {
							IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
							String[] labels = {IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL};
							MessageDialog dialog = new MessageDialog(window.getShell(),
											WIZARD_PROJECT_REMOVE_TITLE, null,
											WIZARD_PROJECT_REMOVE_DESCRIPTION,
											MessageDialog.QUESTION, labels, 1);

							if (dialog.open() == Window.OK) {
								try {
									project.removeContext();
								} catch (final CoreException ex) {
									ex.printStackTrace(System.err);
								}
							}
						}
					}
				);
			}
		}
	}

	/**
	 * Return a TomcatProject if this Project has the tomcat nature
	 * Return null if Project has not tomcat nature
	 * @param project IProject
	 * @return TomcatProject
	 */
	private static ITomcatProject create(final IProject project) {

		IJavaProject javaProject = JavaCore.create(project);
		if (javaProject != null) {
			try {
				ITomcatProject result = (ITomcatProject)javaProject.getProject().getNature(NATURE_ID);
				if (result != null) {
					result.setJavaProject(javaProject);
				}
				return result;
			} catch (final CoreException ex) {
				ex.printStackTrace(System.err);
			}
		}
		return null;
	}
}
